Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Keep, count and read per-test results for the required OK tiers (#6104)
Nick Gomez7e675767f16d
diff --git a/.github/scripts/bug-lane-failure-extraction.test.mjs b/.github/scripts/bug-lane-failure-extraction.test.mjsindex f46859d42..8ede01d87 100644--- a/.github/scripts/bug-lane-failure-extraction.test.mjs+++ b/.github/scripts/bug-lane-failure-extraction.test.mjs@@ -62,7 +62,7 @@ function verdictSnippet() {function verdictFor(firstStatus, retryOutcome = 1) {const snippet = verdictSnippet();const chain = snippet.replace(- /if timeout[\s\S]*?--output-logs=errors-only 2>&1/,+ /if timeout[\s\S]*?--output-logs=errors-only --log-prefix=none 2>&1/,`if (exit ${retryOutcome})`,);if (chain === snippet) {diff --git a/.github/scripts/release-cascade-shape.test.mjs b/.github/scripts/release-cascade-shape.test.mjsindex bee2efe83..09a7e0431 100644--- a/.github/scripts/release-cascade-shape.test.mjs+++ b/.github/scripts/release-cascade-shape.test.mjs@@ -130,6 +130,16 @@ function stepLevelIfConditions(source) {return out;}+const STEP_OR_JOB = /(?=^ {6}- |^ {2}\S)/m;+const isContainedUpload = (block) =>+ /^ {8}uses: actions\/upload-artifact@/m.test(block) &&+ /^ {8}continue-on-error: true$/m.test(block);+const shippingSteps = (source) =>+ source+ .split(STEP_OR_JOB)+ .filter((block) => !isContainedUpload(block))+ .join('');+describe('the stable gate is upstream of everything that ships', () => {const names = stepNames(desktopRelease);@@ -160,11 +170,52 @@ describe('the stable gate is upstream of everything that ships', () => {expect(smoke).toBeLessThan(indexOfStep(names, 'Announce stable release to Discord'));});+ test('a contained artifact upload after the smoke gate ships nothing, and an uncontained one is a shipping step', () => {+ const gate = desktopRelease.indexOf('- name: Smoke the packaged DMG');+ expect(gate, 'the packaged DMG smoke step').toBeGreaterThan(-1);+ const afterGate = desktopRelease.slice(gate);+ const consumers = afterGate.indexOf(' release-consumers:');+ expect(consumers, 'the release-consumers job after the smoke gate').toBeGreaterThan(-1);+ const span = afterGate.slice(0, consumers);+ const contained = span.split(STEP_OR_JOB).filter(isContainedUpload);+ expect(contained.length).toBeGreaterThan(0);+ const [first] = contained;+ const condition = stepLevelIfConditions(first)[0];+ expect(stepLevelIfConditions(shippingSteps(span))).not.toContain(condition);+ const uncontained = span.replace(first, () =>+ first.replace(/^ {8}continue-on-error: true\n/m, ''),+ );+ expect(uncontained).not.toBe(span);+ expect(stepLevelIfConditions(shippingSteps(uncontained))).toContain(condition);+ });++ test('a step after the smoke gate that keeps continue-on-error but downloads an artifact is a shipping step', () => {+ const gate = desktopRelease.indexOf('- name: Smoke the packaged DMG');+ expect(gate, 'the packaged DMG smoke step').toBeGreaterThan(-1);+ const afterGate = desktopRelease.slice(gate);+ const consumers = afterGate.indexOf(' release-consumers:');+ expect(consumers, 'the release-consumers job after the smoke gate').toBeGreaterThan(-1);+ const span = afterGate.slice(0, consumers);+ const [first] = span.split(STEP_OR_JOB).filter(isContainedUpload);+ expect(first, 'a contained artifact upload after the smoke gate').toBeDefined();+ const condition = stepLevelIfConditions(first)[0];+ expect(condition, 'the contained upload carries a step-level if:').toBeTypeOf('string');+ expect(stepLevelIfConditions(shippingSteps(span))).not.toContain(condition);+ const downloaded = first.replace(+ /^ {8}uses: actions\/upload-artifact@/m,+ ' uses: actions/download-artifact@',+ );+ expect(downloaded).not.toBe(first);+ expect(downloaded).toMatch(/^ {8}continue-on-error: true$/m);+ const download = span.replace(first, () => downloaded);+ expect(stepLevelIfConditions(shippingSteps(download))).toContain(condition);+ });+test('no shipping STEP opts out of the implicit success() guard', () => {const afterGate = desktopRelease.slice(desktopRelease.indexOf('- name: Smoke the packaged DMG'),);- const shipping = afterGate.slice(0, afterGate.indexOf(' release-consumers:'));+ const shipping = shippingSteps(afterGate.slice(0, afterGate.indexOf(' release-consumers:')));const stepIfs = stepLevelIfConditions(shipping);expect(stepIfs.length).toBeGreaterThan(0);for (const condition of stepIfs) {@@ -181,7 +232,7 @@ describe('the stable gate is upstream of everything that ships', () => {const afterGate = desktopRelease.slice(desktopRelease.indexOf('- name: Smoke the packaged DMG'),);- const shipping = afterGate.slice(0, afterGate.indexOf(' release-consumers:'));+ const shipping = shippingSteps(afterGate.slice(0, afterGate.indexOf(' release-consumers:')));const conditions = stepLevelIfConditions(shipping);const shippingConditions = conditions.filter((c) => c !== "steps.channel.outputs.channel == 'latest'",diff --git a/.github/workflows/bug-lane-verify.yml b/.github/workflows/bug-lane-verify.ymlindex c03c2bc15..3896b97ca 100644--- a/.github/workflows/bug-lane-verify.yml+++ b/.github/workflows/bug-lane-verify.yml@@ -359,7 +359,7 @@ jobs:TIER_BUDGET_SECONDS=1500FIRST_STATUS=0timeout --foreground --kill-after=10s "${TIER_BUDGET_SECONDS}s" \- pnpm exec turbo run typecheck test test:uncached --concurrency=2 --continue --output-logs=errors-only \+ pnpm exec turbo run typecheck test test:uncached --concurrency=2 --continue --output-logs=errors-only --log-prefix=none \|| FIRST_STATUS=$?RETRY_STATUS=0if [[ "$FIRST_STATUS" -ne 0 ]]; then@@ -376,7 +376,7 @@ jobs:;;*)if timeout --foreground --kill-after=10s "${TIER_BUDGET_SECONDS}s" \- pnpm exec turbo run typecheck test test:uncached --concurrency=2 --output-logs=errors-only 2>&1 | tee "$RETRY_LOG"; then+ pnpm exec turbo run typecheck test test:uncached --concurrency=2 --output-logs=errors-only --log-prefix=none 2>&1 | tee "$RETRY_LOG"; thenRETRY_STATUS=0else# Read BEFORE any other command: the next one clobbers it.@@ -472,6 +472,21 @@ jobs:fifi+ - name: Upload per-test results+ if: ${{ !cancelled() }}+ continue-on-error: true+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: ok-per-test-results-bug-lane-verify-attempt${{ github.run_attempt }}+ path: |+ test-results/vitest-*.json+ docs/test-results/vitest-*.json+ packages/*/test-results/vitest-*.json+ packages/*/test-results/node-test-*.xml+ packages/md-conformance/md-audit/test-results/vitest-*.json+ retention-days: 14+ if-no-files-found: warn+- name: Dispatch the point release (or log what would ship)if: steps.verify.outputs.verdict == 'pass'env:diff --git a/.github/workflows/desktop-build-win-linux.yml b/.github/workflows/desktop-build-win-linux.ymlindex 0e7194b41..4d91e0ab7 100644--- a/.github/workflows/desktop-build-win-linux.yml+++ b/.github/workflows/desktop-build-win-linux.yml@@ -400,6 +400,16 @@ jobs:retention-days: 14if-no-files-found: error+ - name: Upload per-test results+ if: ${{ !cancelled() }}+ continue-on-error: true+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: ok-per-test-results-desktop-build-windows-attempt${{ github.run_attempt }}+ path: packages/desktop/test-results/vitest-*.json+ retention-days: 14+ if-no-files-found: warn+# Two cells, each on a NATIVE runner for its arch. Cross-compiling the arm64# native deps from an x64 host is impractical (pnpm installs only the# host-matching `@parcel/watcher-*` prebuild, and the generated Linux config@@ -573,6 +583,16 @@ jobs:retention-days: 14if-no-files-found: error+ - name: Upload per-test results+ if: ${{ !cancelled() }}+ continue-on-error: true+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: ok-per-test-results-desktop-build-linux-${{ matrix.arch }}-attempt${{ github.run_attempt }}+ path: packages/desktop/test-results/vitest-*.json+ retention-days: 14+ if-no-files-found: warn+# No Linux update-metadata upload: these are unsigned QA artifacts,# never published, so their `latest-linux*.yml` files have no consumer.# The release path (desktop-release.yml) uploads the Linux manifests —diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex 86cb0fbdd..4621649e1 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -1043,6 +1043,16 @@ jobs:retention-days: 14if-no-files-found: error+ - name: Upload per-test results+ if: ${{ !cancelled() && steps.dmg_smoke.outcome != 'skipped' }}+ continue-on-error: true+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: ok-per-test-results-desktop-release-macos-${{ matrix.variant }}-attempt${{ github.run_attempt }}+ path: packages/desktop/test-results/desktop-smoke-packaged-results.json+ retention-days: 14+ if-no-files-found: warn+build-windows:needs: prepareif: contains(needs.prepare.outputs.platforms, 'windows')@@ -1364,6 +1374,16 @@ jobs:retention-days: 14if-no-files-found: error+ - name: Upload per-test results+ if: ${{ !cancelled() && steps.winterm.outputs.ships == 'true' }}+ continue-on-error: true+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: ok-per-test-results-desktop-release-windows-${{ matrix.variant }}-attempt${{ github.run_attempt }}+ path: packages/desktop/test-results/vitest-*.json+ retention-days: 14+ if-no-files-found: warn+# Two cells, each on a NATIVE runner for its arch. Cross-compiling the arm64# native deps from an x64 host is impractical (pnpm installs only the# host-matching `@parcel/watcher-*` prebuild, and the generated Linux config@@ -1600,6 +1620,16 @@ jobs:retention-days: 14if-no-files-found: error+ - name: Upload per-test results+ if: ${{ !cancelled() }}+ continue-on-error: true+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: ok-per-test-results-desktop-release-linux-${{ matrix.arch }}-${{ matrix.variant }}-attempt${{ github.run_attempt }}+ path: packages/desktop/test-results/vitest-*.json+ retention-days: 14+ if-no-files-found: warn+# The single publication point: nothing above this job touches the GitHub# Release. Downloads every platform's staged assets, asserts the complete# cross-platform inventory, uploads, then re-queries the Release anddiff --git a/.github/workflows/select-beta-to-promote.yml b/.github/workflows/select-beta-to-promote.ymlindex 2695e910e..d58621833 100644--- a/.github/workflows/select-beta-to-promote.yml+++ b/.github/workflows/select-beta-to-promote.yml@@ -432,6 +432,16 @@ jobs:echo "::notice::Fast tier refused for ${CANDIDATE} (verdict=${VERDICT:-unknown}). The 24h tier is unaffected; this beta promotes normally once it has soaked."echo "Fast tier refused for ${CANDIDATE}; verdict=${VERDICT:-unknown}. The aggregate incident reporter owns Slack notifications." >> "$GITHUB_STEP_SUMMARY"+ - name: Upload per-test results+ if: ${{ !cancelled() }}+ continue-on-error: true+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: ok-per-test-results-select-beta-to-promote-attempt${{ github.run_attempt }}+ path: packages/desktop/test-results/desktop-smoke-packaged-results.json+ retention-days: 14+ if-no-files-found: warn+dispatch-fast-tier-candidate:name: Dispatch the smoke-proven fast-tier candidateneeds: [evaluate, smoke-fast-tier-candidate]diff --git a/packages/native-config/package.json b/packages/native-config/package.jsonindex bea806938..dede7de53 100644--- a/packages/native-config/package.json+++ b/packages/native-config/package.json@@ -27,7 +27,7 @@"scripts": {"build": "node scripts/build.mjs --release","build:debug": "node scripts/build.mjs",- "test": "cargo test && node --test scripts/build.test.mjs && node --test scripts/toolchain-guard.test.mjs"+ "test": "cargo test && node scripts/make-test-results-dir.mjs && node --test --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=test-results/node-test-build.xml scripts/build.test.mjs && node --test --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=test-results/node-test-toolchain-guard.xml scripts/toolchain-guard.test.mjs"},"devDependencies": {"@napi-rs/cli": "^3.7.2"diff --git a/packages/native-config/scripts/make-test-results-dir.mjs b/packages/native-config/scripts/make-test-results-dir.mjsnew file mode 100644index 000000000..0867fd42c--- /dev/null+++ b/packages/native-config/scripts/make-test-results-dir.mjs@@ -0,0 +1,3 @@+import { mkdirSync } from 'node:fs';++mkdirSync('test-results', { recursive: true });diff --git a/packages/native-config/turbo.json b/packages/native-config/turbo.jsonindex 586059a96..a7ee20a69 100644--- a/packages/native-config/turbo.json+++ b/packages/native-config/turbo.json@@ -17,7 +17,7 @@"test": {"dependsOn": ["build"],"inputs": ["$TURBO_DEFAULT$", "!README.md", "$TURBO_ROOT$/rust-toolchain.toml"],- "outputs": []+ "outputs": ["test-results/node-test-build.xml", "test-results/node-test-toolchain-guard.xml"]}}}diff --git a/test-support/setup-files-contract.test.ts b/test-support/setup-files-contract.test.tsindex e3c6190a6..ce6469e11 100644--- a/test-support/setup-files-contract.test.ts+++ b/test-support/setup-files-contract.test.ts@@ -1,15 +1,22 @@-import { execFileSync } from 'node:child_process';-import { existsSync } from 'node:fs';-import { basename, join } from 'node:path';-import { fileURLToPath, pathToFileURL } from 'node:url';-import { describe, expect, test } from 'vitest';-import { gitCleanEnv } from '../scripts/git-clean-env.mjs';+import { existsSync, writeFileSync } from 'node:fs';+import { basename, join, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterAll, describe, expect, test } from 'vitest';+import { createTempDirFactory } from './temp-dir.test-helper';import { okVitestBase } from './vitest.base';+import {+ isTestConfig,+ type ProjectReading,+ readConfigProjects,+ trackedConfigs,+ trackedFiles,+} from './vitest-configs.test-helper';const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url));-const CONFIG_FILENAME = /(?:^|\.)vite(st)?[\w.-]*\.config\.m?[jt]s$/;-const TEST_CONFIG_FILENAME = /(?:^|\.)vitest[\w.-]*\.config\.m?[jt]s$/;+const BASE_MODULE = fileURLToPath(new URL('./vitest.base.ts', import.meta.url))+ .split(sep)+ .join('/');const KNOWN_TEST_PROJECTS = ['docs/vitest.config.ts',@@ -56,58 +63,67 @@ const BROWSER_PROJECT_SETUP_FILES: Readonly<Record<string, readonly string[]>> =const isBrowserProject = (relPath: string): boolean =>Object.hasOwn(BROWSER_PROJECT_SETUP_FILES, relPath);-const isTestConfig = (relPath: string): boolean => TEST_CONFIG_FILENAME.test(basename(relPath));--function trackedFiles(pathspecs: readonly string[]): string[] {- return execFileSync('git', ['ls-files', '-z', '--', ...pathspecs], {- cwd: REPO_ROOT,- env: gitCleanEnv(),- encoding: 'utf8',- })- .split('\0')- .filter((relPath) => relPath !== '');-}--function findConfigs(): string[] {- return trackedFiles(['*.config.ts', '*.config.mts', '*.config.js', '*.config.mjs'])- .filter((relPath) => CONFIG_FILENAME.test(basename(relPath)))- .sort();-}--const tracksFilesThePublicTreeOmits = trackedFiles(['*.private.*']).length > 0;+const tracksFilesThePublicTreeOmits = trackedFiles(REPO_ROOT, ['*.private.*']).length > 0;const EXPECTED_TEST_PROJECTS = tracksFilesThePublicTreeOmits? [...KNOWN_TEST_PROJECTS, ...TEST_PROJECTS_OUTSIDE_THE_PUBLIC_TREE]: KNOWN_TEST_PROJECTS;-type TestOptions = { name?: unknown; setupFiles?: unknown; projects?: unknown };-function setupFileList(setupFiles: unknown): string[] {if (setupFiles === undefined) return [];return (Array.isArray(setupFiles) ? setupFiles : [setupFiles]).map(String);}-async function resolveSetupFiles(- relPath: string,-): Promise<Array<{ project: string; setupFiles: string[] }>> {- const loaded: unknown = await import(pathToFileURL(join(REPO_ROOT, relPath)).href);- const exported = (loaded as { default?: unknown }).default ?? loaded;- const config =- typeof exported === 'function' ? await exported({ command: 'serve', mode: 'test' }) : exported;- const test = (config as { test?: TestOptions }).test;- if (!Array.isArray(test?.projects)) {- return [{ project: relPath, setupFiles: setupFileList(test?.setupFiles) }];- }- return test.projects.map((project: unknown, index: number) => {- const inline = (project as { test?: TestOptions } | null)?.test;- return {- project: `${relPath} project ${String(inline?.name ?? index)}`,- setupFiles: setupFileList(inline?.setupFiles),- };- });+const readSetupFiles = (root: string, relPath: string): Promise<Array<ProjectReading<string>>> =>+ readConfigProjects(root, relPath, (options) => setupFileList(options.test?.setupFiles));++const unresolvedProblem = (project: string, reference: string): string =>+ `${project} is resolved from ${reference}, which this check does not follow; declare the project inline.`;++function sharedSetupProblems(reading: ProjectReading<string>): string[] {+ if (reading.kind === 'unresolved') return [unresolvedProblem(reading.project, reading.reference)];+ const missing = okVitestBase.test.setupFiles.filter((entry) => !reading.values.includes(entry));+ if (missing.length === 0) return [];+ return [+ `${reading.project} omits [${missing.join(', ')}], which the shared base installs; it resolves ` ++ `[${reading.values.join(', ')}]. Build it from okVitestBase.test.setupFiles rather than listing entries by hand.`,+ ];}-const configs = findConfigs();+function browserSetupProblems(+ reading: ProjectReading<string>,+ required: readonly string[],+): string[] {+ if (reading.kind === 'unresolved') return [unresolvedProblem(reading.project, reading.reference)];+ const names = reading.values.map((entry) => basename(entry));+ const absent = required.filter((name) => !names.includes(name));+ const nodeOnly = reading.values.filter((entry) => okVitestBase.test.setupFiles.includes(entry));+ return [+ ...(absent.length === 0+ ? []+ : [+ `${reading.project} resolves [${reading.values.join(', ')}] without its browser setup [${absent.join(', ')}].`,+ ]),+ ...(nodeOnly.length === 0+ ? []+ : [+ `${reading.project} loads the Node-only shared setup file(s) [${nodeOnly.join(', ')}] into the browser.`,+ ]),+ ];+}++const makeTempDir = createTempDirFactory(afterAll);++function plantConfig(name: string, body: readonly string[]): string {+ const root = makeTempDir('ok-setup-files-contract-');+ writeFileSync(+ join(root, name),+ [`import { okVitestBase } from ${JSON.stringify(BASE_MODULE)};`, ...body, ''].join('\n'),+ );+ return root;+}++const configs = trackedConfigs(REPO_ROOT);describe('vitest setupFiles contract', () => {test('every tracked config is present in the working tree', () => {@@ -153,32 +169,110 @@ describe('vitest setupFiles contract', () => {test.each(configs.filter((relPath) => isTestConfig(relPath) && !isBrowserProject(relPath)))('%s resolves setupFiles containing every entry the shared base installs',async (relPath) => {- for (const { project, setupFiles } of await resolveSetupFiles(relPath)) {- const missing = okVitestBase.test.setupFiles.filter((entry) => !setupFiles.includes(entry));- expect(- missing,- `${project} omits ${missing.length} shared setup file(s); it resolves ` +- `[${setupFiles.join(', ')}]. Build it from okVitestBase.test.setupFiles ` +- 'rather than listing entries by hand.',- ).toEqual([]);- }+ const readings = await readSetupFiles(REPO_ROOT, relPath);+ expect(readings.length, `${relPath} resolved no project`).toBeGreaterThan(0);+ expect(readings.flatMap(sharedSetupProblems)).toEqual([]);},);test.each(Object.entries(BROWSER_PROJECT_SETUP_FILES))('%s resolves its browser setup files and none of the Node-only setup files the shared base installs',async (relPath, required) => {- for (const { project, setupFiles } of await resolveSetupFiles(relPath)) {- const names = setupFiles.map((entry) => basename(entry));- expect(- required.filter((name) => !names.includes(name)),- `${project} resolves [${setupFiles.join(', ')}] without its browser setup.`,- ).toEqual([]);- expect(- setupFiles.filter((entry) => okVitestBase.test.setupFiles.includes(entry)),- `${project} loads a Node-only shared setup file into the browser.`,- ).toEqual([]);- }+ const readings = await readSetupFiles(REPO_ROOT, relPath);+ expect(readings.length, `${relPath} resolved no project`).toBeGreaterThan(0);+ expect(readings.flatMap((reading) => browserSetupProblems(reading, required))).toEqual([]);},);});++describe('a projects config is judged by the setup files Vitest gives each project', () => {+ test('a project inherits the setup files of the config that declares it, before its own, and one that sets extends: false does not', async () => {+ const config = 'vitest.projects.config.mjs';+ const root = plantConfig(config, [+ 'export default {',+ ' test: {',+ ' setupFiles: okVitestBase.test.setupFiles,',+ ' projects: [',+ " { test: { name: 'inherits', setupFiles: ['./project-setup.ts'] } },",+ " { extends: false, test: { name: 'extends-false', setupFiles: ['./project-setup.ts'] } },",+ ' ],',+ ' },',+ '};',+ ]);+ const readings = await readSetupFiles(root, config);+ expect(readings).toEqual([+ {+ kind: 'resolved',+ project: `${config} project inherits`,+ values: [...okVitestBase.test.setupFiles, './project-setup.ts'],+ },+ {+ kind: 'resolved',+ project: `${config} project extends-false`,+ values: ['./project-setup.ts'],+ },+ ]);+ expect(readings.map(sharedSetupProblems)).toEqual([+ [],+ [+ expect.stringContaining(+ `${config} project extends-false omits [${okVitestBase.test.setupFiles.join(', ')}]`,+ ),+ ],+ ]);+ });++ test('a project named by a path, or one that extends another config file, is reported as unresolved rather than judged', async () => {+ const config = 'vitest.by-reference.config.mjs';+ const root = plantConfig(config, [+ 'export default {',+ ' test: {',+ ' setupFiles: okVitestBase.test.setupFiles,',+ ' projects: [',+ " './vitest.other.config.mjs',",+ " { extends: './vitest.other.config.mjs', test: { name: 'extends-file' } },",+ ' ],',+ ' },',+ '};',+ ]);+ const readings = await readSetupFiles(root, config);+ const unresolved = [+ `${config} project 0 is resolved from ./vitest.other.config.mjs`,+ `${config} project extends-file is resolved from ./vitest.other.config.mjs`,+ ].map((problem) => [expect.stringContaining(problem)]);+ expect(readings.map(sharedSetupProblems)).toEqual(unresolved);+ expect(readings.map((reading) => browserSetupProblems(reading, ['browser-setup.ts']))).toEqual(+ unresolved,+ );+ });++ test('a browser project is reported when it lacks its browser setup or resolves a Node-only shared setup file', async () => {+ const config = 'vitest.browser.config.mjs';+ const root = plantConfig(config, [+ 'export default {',+ ' test: {',+ ' setupFiles: okVitestBase.test.setupFiles,',+ ' projects: [',+ " { extends: false, test: { name: 'browser-only', setupFiles: ['./browser-setup.ts'] } },",+ " { test: { name: 'inherits-node-only', setupFiles: ['./browser-setup.ts'] } },",+ " { extends: false, test: { name: 'no-browser-setup', setupFiles: ['./other-setup.ts'] } },",+ ' ],',+ ' },',+ '};',+ ]);+ const readings = await readSetupFiles(root, config);+ expect(readings.map((reading) => browserSetupProblems(reading, ['browser-setup.ts']))).toEqual([+ [],+ [+ expect.stringContaining(+ `${config} project inherits-node-only loads the Node-only shared setup file(s) [${okVitestBase.test.setupFiles.join(', ')}]`,+ ),+ ],+ [+ expect.stringContaining(+ `${config} project no-browser-setup resolves [./other-setup.ts] without its browser setup [browser-setup.ts]`,+ ),+ ],+ ]);+ });+});diff --git a/test-support/uncached-tier-floor.ts b/test-support/uncached-tier-floor.tsindex 44a0bccb8..7fddb0838 100644--- a/test-support/uncached-tier-floor.ts+++ b/test-support/uncached-tier-floor.ts@@ -1,93 +1,14 @@-import { relative, sep } from 'node:path';import type { Plugin } from 'vitest/config';-import type {- Reporter,- TestCase,- TestModule,- TestRunEndReason,- TestSuite,- VitestPluginContext,-} from 'vitest/node';+import type { Reporter, TestCase, TestRunEndReason, VitestPluginContext } from 'vitest/node';import { UNCACHED_TIER_CONFIG } from './uncached-tier';+import { executed, sumAcrossFiles, tallyVitestRun, type VitestFileTally } from './vitest-run-tally';const UNCACHED_TIER_AUTHOR_RULE ='A tier test must execute wherever the tier runs; if its subject is absent from the public mirror, name the file <name>.private.uncached.test.ts; never skip a test, or condition its definition or body, on a presence probe.';-type UncachedTierFileTally = {- path: string;- passed: number;- failed: number;- skipped: number;- todo: number;- unfinished: number;- stopped: number;- emptySkippedSuites: string[];- emptyStoppedSuites: string[];- failedDuringCollection: boolean;-};-type UncachedTierVerdict = { refused: boolean; message: string };-function failedWithOwnError(entity: TestSuite | TestModule): boolean {- return entity.state() === 'failed' && entity.errors().length > 0;-}--function stoppedByFailure(entity: TestCase | TestSuite): boolean {- if (entity.options.mode !== 'run') return false;- let enclosing: TestSuite | TestModule = entity.parent;- while (!failedWithOwnError(enclosing)) {- if (enclosing.type === 'module') return false;- enclosing = enclosing.parent;- }- return true;-}--function tallyUncachedTierRun(- testModules: ReadonlyArray<TestModule>,- root: string,- started: WeakSet<TestCase>,-): UncachedTierFileTally[] {- return testModules.map((testModule) => {- const tally: UncachedTierFileTally = {- path: relative(root, testModule.moduleId).split(sep).join('/'),- passed: 0,- failed: 0,- skipped: 0,- todo: 0,- unfinished: 0,- stopped: 0,- emptySkippedSuites: [],- emptyStoppedSuites: [],- failedDuringCollection: false,- };- for (const test of testModule.children.allTests()) {- const { state } = test.result();- if (state === 'passed') tally.passed += 1;- else if (state === 'failed') tally.failed += 1;- else if (state === 'pending') tally.unfinished += 1;- else if (state !== 'skipped') {- throw new Error(`test "${test.fullName}" in ${tally.path} reports an unknown state`);- } else if (test.options.mode === 'todo') tally.todo += 1;- else if (!started.has(test) && stoppedByFailure(test)) tally.stopped += 1;- else tally.skipped += 1;- }- for (const suite of testModule.children.allSuites()) {- if (suite.state() === 'skipped' && suite.children.allTests().next().done) {- if (stoppedByFailure(suite)) tally.emptyStoppedSuites.push(suite.fullName);- else tally.emptySkippedSuites.push(suite.fullName);- }- }- tally.failedDuringCollection =- failedWithOwnError(testModule) && testModule.diagnostic().collectDuration === 0;- return tally;- });-}--function executed(file: UncachedTierFileTally): number {- return file.passed + file.failed;-}--function notExecuted(file: UncachedTierFileTally): string[] {+function notExecuted(file: VitestFileTally): string[] {return [...(file.skipped > 0 ? [`${file.skipped} skipped`] : []),...(file.todo > 0 ? [`${file.todo} todo`] : []),@@ -96,7 +17,7 @@ function notExecuted(file: UncachedTierFileTally): string[] {];}-function failureParts(file: UncachedTierFileTally): string[] {+function failureParts(file: VitestFileTally): string[] {return [...(file.failedDuringCollection ? ['failed during collection'] : []),...(file.stopped > 0 ? [`${file.stopped} stopped by a failure`] : []),@@ -104,12 +25,8 @@ function failureParts(file: UncachedTierFileTally): string[] {];}-function sum(files: UncachedTierFileTally[], count: (file: UncachedTierFileTally) => number) {- return files.reduce((total, file) => total + count(file), 0);-}-function uncachedTierVerdict(- files: UncachedTierFileTally[],+ files: VitestFileTally[],{ testNamePattern, reason }: { testNamePattern?: string; reason?: TestRunEndReason } = {},): UncachedTierVerdict {if (files.length === 0) {@@ -118,11 +35,11 @@ function uncachedTierVerdict(message: `${UNCACHED_TIER_CONFIG}: the tier fails this run because it ran no test file. Run the tier whole, or narrow it with a file filter that names an existing .uncached.test file.`,};}- const ran = sum(files, executed);- const skipped = sum(files, (file) => file.skipped);- const todo = sum(files, (file) => file.todo);- const unfinished = sum(files, (file) => file.unfinished);- const stopped = sum(files, (file) => file.stopped);+ const ran = sumAcrossFiles(files, executed);+ const skipped = sumAcrossFiles(files, (file) => file.skipped);+ const todo = sumAcrossFiles(files, (file) => file.todo);+ const unfinished = sumAcrossFiles(files, (file) => file.unfinished);+ const stopped = sumAcrossFiles(files, (file) => file.stopped);const collected = ran + skipped + todo + unfinished + stopped;if (reason === 'interrupted') {return {@@ -136,7 +53,7 @@ function uncachedTierVerdict(if (offending.length === 0) {return {refused: false,- message: `uncached tier: every collected test executed (${ran} of ${collected}; ${sum(files, (file) => file.passed)} passed, ${sum(files, (file) => file.failed)} failed; ${files.length} files).`,+ message: `uncached tier: every collected test executed (${ran} of ${collected}; ${sumAcrossFiles(files, (file) => file.passed)} passed, ${sumAcrossFiles(files, (file) => file.failed)} failed; ${files.length} files).`,};}const lines = offending.map((file) => {@@ -180,13 +97,10 @@ function floorReporter(vitest: VitestPluginContext['vitest']): Reporter {let verdict: UncachedTierVerdict;try {const pattern = vitest.config.testNamePattern;- verdict = uncachedTierVerdict(- tallyUncachedTierRun(testModules, vitest.config.root, started),- {- testNamePattern: pattern === undefined ? undefined : pattern.source,- reason,- },- );+ verdict = uncachedTierVerdict(tallyVitestRun(testModules, vitest.config.root, started), {+ testNamePattern: pattern === undefined ? undefined : pattern.source,+ reason,+ });} catch (error) {verdict = {refused: true,diff --git a/test-support/vitest-configs.test-helper.ts b/test-support/vitest-configs.test-helper.tsnew file mode 100644index 000000000..2993a8b73--- /dev/null+++ b/test-support/vitest-configs.test-helper.ts@@ -0,0 +1,89 @@+import { execFileSync } from 'node:child_process';+import { basename, join } from 'node:path';+import { pathToFileURL } from 'node:url';+import type { ConfigEnv } from 'vitest/config';+import { gitCleanEnv } from '../scripts/git-clean-env.mjs';++const CONFIG_FILENAME = /(?:^|\.)vite(st)?[\w.-]*\.config\.m?[jt]s$/;+const TEST_CONFIG_FILENAME = /(?:^|\.)vitest[\w.-]*\.config\.m?[jt]s$/;++const VITEST_CONFIG_ENV: ConfigEnv = {+ command: 'serve',+ mode: 'test',+ isPreview: false,+ isSsrBuild: false,+};++type ConfigOptions = {+ plugins?: unknown;+ extends?: unknown;+ test?: { name?: unknown; setupFiles?: unknown; projects?: unknown };+};++export type ProjectReading<Value> =+ | { kind: 'resolved'; project: string; values: readonly Value[] }+ | { kind: 'unresolved'; project: string; reference: string };++export const isTestConfig = (relPath: string): boolean =>+ TEST_CONFIG_FILENAME.test(basename(relPath));++export function trackedFiles(root: string, pathspecs: readonly string[]): string[] {+ return execFileSync('git', ['ls-files', '-z', '--', ...pathspecs], {+ cwd: root,+ env: gitCleanEnv(),+ encoding: 'utf8',+ })+ .split('\0')+ .filter((relPath) => relPath !== '');+}++export function trackedConfigs(root: string): string[] {+ return trackedFiles(root, ['*.config.ts', '*.config.mts', '*.config.js', '*.config.mjs'])+ .filter((relPath) => CONFIG_FILENAME.test(basename(relPath)))+ .sort();+}++async function loadConfig(path: string): Promise<unknown> {+ const loaded: unknown = await import(pathToFileURL(path).href);+ const exported = (loaded as { default?: unknown }).default ?? loaded;+ return typeof exported === 'function' ? await exported(VITEST_CONFIG_ENV) : exported;+}++async function readProject<Value>(+ relPath: string,+ declared: readonly Value[],+ definition: unknown,+ index: number,+ valuesOf: (options: ConfigOptions) => readonly Value[] | Promise<readonly Value[]>,+): Promise<ProjectReading<Value>> {+ if (typeof definition === 'string') {+ return { kind: 'unresolved', project: `${relPath} project ${index}`, reference: definition };+ }+ const project = (await (typeof definition === 'function'+ ? definition(VITEST_CONFIG_ENV)+ : definition)) as ConfigOptions;+ const name = project.test?.name;+ const label = `${relPath} project ${typeof name === 'string' ? name : index}`;+ if (typeof project.extends === 'string') {+ return { kind: 'unresolved', project: label, reference: project.extends };+ }+ const inherited = project.extends === false ? [] : declared;+ return { kind: 'resolved', project: label, values: [...inherited, ...(await valuesOf(project))] };+}++export async function readConfigProjects<Value>(+ root: string,+ relPath: string,+ valuesOf: (options: ConfigOptions) => readonly Value[] | Promise<readonly Value[]>,+): Promise<Array<ProjectReading<Value>>> {+ const config = (await loadConfig(join(root, relPath))) as ConfigOptions;+ const declared = await valuesOf(config);+ const definitions = config.test?.projects;+ if (!Array.isArray(definitions))+ return [{ kind: 'resolved', project: relPath, values: declared }];+ return Promise.all(+ definitions.map((definition: unknown, index: number) =>+ readProject(relPath, declared, definition, index, valuesOf),+ ),+ );+}diff --git a/test-support/vitest-run-evidence-configs.test.ts b/test-support/vitest-run-evidence-configs.test.tsnew file mode 100644index 000000000..73f8db46d--- /dev/null+++ b/test-support/vitest-run-evidence-configs.test.ts@@ -0,0 +1,239 @@+import { writeFileSync } from 'node:fs';+import { join, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterAll, describe, expect, test } from 'vitest';+import { createTempDirFactory } from './temp-dir.test-helper';+import {+ isTestConfig,+ type ProjectReading,+ readConfigProjects,+ trackedConfigs,+} from './vitest-configs.test-helper';+import { vitestRunEvidence } from './vitest-run-evidence';++const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url));++const BASE_MODULE = fileURLToPath(new URL('./vitest.base.ts', import.meta.url))+ .split(sep)+ .join('/');++const RUN_EVIDENCE_PLUGIN = vitestRunEvidence().name;++type ContractReading = {+ configs: number;+ projects: number;+ findings: readonly ProjectReading<string>[];+};++async function pluginNames(option: unknown): Promise<string[]> {+ const value = await option;+ if (Array.isArray(value)) return (await Promise.all(value.map(pluginNames))).flat();+ return value ? [String((value as { name?: unknown }).name)] : [];+}++const omitsRunEvidence = (reading: ProjectReading<string>): boolean =>+ reading.kind === 'unresolved' || !reading.values.includes(RUN_EVIDENCE_PLUGIN);++function describeFinding(reading: ProjectReading<string>): string {+ switch (reading.kind) {+ case 'resolved':+ return `${reading.project} resolves plugins [${reading.values.join(', ')}] without ${RUN_EVIDENCE_PLUGIN}; spread okVitestBase.plugins into its plugins.`;+ case 'unresolved':+ return `${reading.project} is resolved from ${reading.reference}, which this check does not follow; declare the project inline.`;+ }+}++async function readRunEvidenceContract(+ root: string,+ relPaths: readonly string[],+): Promise<ContractReading> {+ const projects = (+ await Promise.all(+ relPaths.map((relPath) =>+ readConfigProjects(root, relPath, (options) => pluginNames(options.plugins)),+ ),+ )+ ).flat();+ return {+ configs: relPaths.length,+ projects: projects.length,+ findings: projects.filter(omitsRunEvidence),+ };+}++const makeTempDir = createTempDirFactory(afterAll);++function plantConfigs(configs: Record<string, string>): string {+ const root = makeTempDir('ok-vitest-run-evidence-configs-');+ for (const [name, body] of Object.entries(configs)) {+ writeFileSync(+ join(root, name),+ [+ `import { importMetaDirPlugin, okVitestBase } from ${JSON.stringify(BASE_MODULE)};`,+ "const extra = { name: 'ok-fixture:extra' };",+ body,+ '',+ ].join('\n'),+ );+ }+ return root;+}++describe('every Vitest config hands each of its projects the run-evidence plugin', () => {+ test('a config that sets its plugins without spreading the base plugins is named, and configs that spread them pass', async () => {+ const root = plantConfigs({+ 'vitest.keeps-base.config.mjs': 'export default { ...okVitestBase };',+ 'vitest.adds-plugin.config.mjs':+ 'export default { ...okVitestBase, plugins: [...okVitestBase.plugins, extra] };',+ 'vitest.drops-base.config.mjs': 'export default { ...okVitestBase, plugins: [extra] };',+ 'vitest.lists-by-hand.config.mjs':+ 'export default { ...okVitestBase, plugins: [importMetaDirPlugin, extra] };',+ });+ expect(+ await readRunEvidenceContract(root, [+ 'vitest.keeps-base.config.mjs',+ 'vitest.adds-plugin.config.mjs',+ 'vitest.drops-base.config.mjs',+ 'vitest.lists-by-hand.config.mjs',+ ]),+ ).toEqual({+ configs: 4,+ projects: 4,+ findings: [+ { kind: 'resolved', project: 'vitest.drops-base.config.mjs', values: ['ok-fixture:extra'] },+ {+ kind: 'resolved',+ project: 'vitest.lists-by-hand.config.mjs',+ values: ['ok-bun-import-meta-dir', 'ok-fixture:extra'],+ },+ ],+ });+ });++ test("plugins are read the way Vite resolves them, through a factory's nested, awaited and empty entries", async () => {+ const root = plantConfigs({+ 'vitest.nested-keeps.config.mjs':+ 'export default async () => ({ ...okVitestBase, plugins: [false, [Promise.resolve(okVitestBase.plugins)], null] });',+ 'vitest.nested-drops.config.mjs':+ 'export default async () => ({ ...okVitestBase, plugins: [false, [Promise.resolve([extra])], null] });',+ });+ expect(+ await readRunEvidenceContract(root, [+ 'vitest.nested-keeps.config.mjs',+ 'vitest.nested-drops.config.mjs',+ ]),+ ).toEqual({+ configs: 2,+ projects: 2,+ findings: [+ {+ kind: 'resolved',+ project: 'vitest.nested-drops.config.mjs',+ values: ['ok-fixture:extra'],+ },+ ],+ });+ });++ test('each project is read with the plugins Vitest gives it: the declaring config inherited unless extends is false, plus its own', async () => {+ const root = plantConfigs({+ 'vitest.projects.config.mjs': [+ 'export default {',+ ' plugins: okVitestBase.plugins,',+ ' test: {',+ ' projects: [',+ " { test: { name: 'inherits' } },",+ " { extends: true, test: { name: 'extends-true' } },",+ " { extends: false, test: { name: 'extends-false' } },",+ " { extends: false, plugins: okVitestBase.plugins, test: { name: 'extends-false-own' } },",+ " () => ({ extends: false, plugins: [extra], test: { name: 'factory' } }),",+ ' ],',+ ' },',+ '};',+ ].join('\n'),+ 'vitest.root-without.config.mjs': [+ 'export default {',+ ' test: {',+ ' projects: [',+ " { plugins: [...okVitestBase.plugins, extra], test: { name: 'own' } },",+ " { test: { name: 'none' } },",+ ' ],',+ ' },',+ '};',+ ].join('\n'),+ });+ expect(+ await readRunEvidenceContract(root, [+ 'vitest.projects.config.mjs',+ 'vitest.root-without.config.mjs',+ ]),+ ).toEqual({+ configs: 2,+ projects: 7,+ findings: [+ {+ kind: 'resolved',+ project: 'vitest.projects.config.mjs project extends-false',+ values: [],+ },+ {+ kind: 'resolved',+ project: 'vitest.projects.config.mjs project factory',+ values: ['ok-fixture:extra'],+ },+ { kind: 'resolved', project: 'vitest.root-without.config.mjs project none', values: [] },+ ],+ });+ });++ test('a project named by a path, or one that extends another config file, is reported as unresolved rather than passed', async () => {+ const root = plantConfigs({+ 'vitest.keeps-base.config.mjs': 'export default { ...okVitestBase };',+ 'vitest.by-reference.config.mjs': [+ 'export default {',+ ' plugins: okVitestBase.plugins,',+ ' test: {',+ ' projects: [',+ " './vitest.keeps-base.config.mjs',",+ " { extends: './vitest.keeps-base.config.mjs', test: { name: 'extends-file' } },",+ " { test: { name: 'inline' } },",+ ' ],',+ ' },',+ '};',+ ].join('\n'),+ });+ expect(await readRunEvidenceContract(root, ['vitest.by-reference.config.mjs'])).toEqual({+ configs: 1,+ projects: 3,+ findings: [+ {+ kind: 'unresolved',+ project: 'vitest.by-reference.config.mjs project 0',+ reference: './vitest.keeps-base.config.mjs',+ },+ {+ kind: 'unresolved',+ project: 'vitest.by-reference.config.mjs project extends-file',+ reference: './vitest.keeps-base.config.mjs',+ },+ ],+ });+ });++ test('every tracked Vitest config on disk hands the plugin to each of its projects', async () => {+ const tracked = trackedConfigs(REPO_ROOT).filter(isTestConfig);+ const reading = await readRunEvidenceContract(REPO_ROOT, tracked);+ const examined = `the sweep read ${reading.configs} configs and ${reading.projects} projects`;+ expect(+ reading.findings,+ `${examined}; ${reading.findings.map(describeFinding).join(' ')}`,+ ).toEqual([]);+ expect(reading.configs, examined).toBe(tracked.length);+ expect(tracked, 'the sweep must reach the tier that composes projects').toContain(+ 'vitest.uncached.config.ts',+ );+ expect(reading.projects, `${examined}, so it never walked into a project`).toBeGreaterThan(+ reading.configs,+ );+ });+});diff --git a/test-support/vitest-run-evidence.test.ts b/test-support/vitest-run-evidence.test.tsnew file mode 100644index 000000000..b607ef2e6--- /dev/null+++ b/test-support/vitest-run-evidence.test.ts@@ -0,0 +1,581 @@+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, dirname, join, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterEach, describe, expect, test } from 'vitest';+import { type ChildRun, runChildWithSilenceBound } from './child-silence-bound.test-helper';+import { VITEST_RUN_EVIDENCE_OWNER_ENV } from './vitest-run-evidence';++const VITEST_CLI = resolve(+ dirname(fileURLToPath(import.meta.resolve('vitest/package.json'))),+ 'vitest.mjs',+);+const BASE_MODULE = fileURLToPath(new URL('./vitest.base.ts', import.meta.url))+ .split(sep)+ .join('/');+const CHILD_SILENCE_BOUND_MS = 300_000;+const CHILD_OUTPUT_LIMIT_BYTES = 64 * 1024 * 1024;+const BOUNDED_BY_CHILD_SILENCE = 0;++const RUN_IDENTITY_ENV = [+ VITEST_RUN_EVIDENCE_OWNER_ENV,+ 'GITHUB_ACTIONS',+ 'GITHUB_STEP_SUMMARY',+ 'GITHUB_RUN_ID',+ 'GITHUB_RUN_ATTEMPT',+ 'GITHUB_JOB',+ 'TURBO_HASH',+ 'npm_lifecycle_event',+];++function childEnv(overrides: Record<string, string>): NodeJS.ProcessEnv {+ const env: NodeJS.ProcessEnv = { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' };+ for (const name of RUN_IDENTITY_ENV) delete env[name];+ return { ...env, ...overrides };+}++function runVitest(+ signal: AbortSignal,+ root: string,+ args: string[],+ overrides: Record<string, string>,+): Promise<ChildRun> {+ return runChildWithSilenceBound(process.execPath, [VITEST_CLI, ...args], {+ cwd: root,+ env: childEnv(overrides),+ signal,+ silenceBoundMs: CHILD_SILENCE_BOUND_MS,+ outputLimitBytes: CHILD_OUTPUT_LIMIT_BYTES,+ });+}++const roots: string[] = [];++afterEach(() => {+ while (roots.length > 0) rmSync(roots.pop() as string, { recursive: true, force: true });+});++const BASE_CONFIG = [+ `import { okVitestBase } from ${JSON.stringify(BASE_MODULE)};`,+ 'export default {',+ ' ...okVitestBase,',+ " test: { ...okVitestBase.test, globals: true, include: ['*.fixture.test.mjs'] },",+ '};',+ '',+].join('\n');++function writePackage(+ root: string,+ name: string,+ files: Record<string, string>,+ config: string,+): void {+ writeFileSync(join(root, 'package.json'), `${JSON.stringify({ name, private: true })}\n`);+ writeFileSync(join(root, 'vitest.config.mjs'), config);+ for (const [file, body] of Object.entries(files)) {+ mkdirSync(dirname(join(root, file)), { recursive: true });+ writeFileSync(join(root, file), body);+ }+}++function fixturePackage(+ name: string,+ files: Record<string, string>,+ config: string = BASE_CONFIG,+): string {+ const root = mkdtempSync(join(tmpdir(), 'ok-vitest-run-evidence-'));+ roots.push(root);+ writePackage(root, name, files, config);+ return root;+}++function errorAnnotations(run: ChildRun): string[] {+ return run.output.split('\n').filter((line) => line.startsWith('::error'));+}++type VitestJsonReport = {+ numTotalTests: number;+ numPassedTests: number;+ numPendingTests: number;+ numTodoTests: number;+ testResults: Array<{ name: string }>;+};++function readJson<T>(path: string): T {+ return JSON.parse(readFileSync(path, 'utf8')) as T;+}++function reportDirectory(root: string): string[] {+ const dir = join(root, 'test-results');+ return existsSync(dir) ? readdirSync(dir).sort() : [];+}++const ALL_SKIP = {+ 'all-skip.fixture.test.mjs': [+ "test.skip('skipped where it is declared', () => { expect(1).toBe(1); });",+ "test('skips itself at runtime', (ctx) => { ctx.skip(); expect(1).toBe(2); });",+ "test.todo('not written yet');",+ '',+ ].join('\n'),+};++const ONE_EXECUTED = {+ 'executed.fixture.test.mjs': "test('executes', () => { expect(1).toBe(1); });\n",+};++const IMPORT_FAILS = {+ 'import-fails.fixture.test.mjs': [+ "import './no-module-is-named-this.mjs';",+ "test('never collected', () => { expect(1).toBe(1); });",+ '',+ ].join('\n'),+};++const NO_TEST_NAMED = 'no fixture test is named this';++describe('on GitHub Actions, a Vitest run that executed no test fails', () => {+ test(+ 'a package whose every test skips fails with one error annotation naming the package, the script and the counts',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/all-skip', ALL_SKIP);+ const run = await runVitest(signal, root, ['run'], {+ GITHUB_ACTIONS: 'true',+ npm_lifecycle_event: 'test:unit',+ });+ expect(run.signal).toBeNull();+ expect(run.status, run.output).toBe(1);+ const annotations = errorAnnotations(run);+ expect(annotations, run.output).toHaveLength(1);+ expect(annotations[0]).toContain('@ok-fixture/all-skip');+ expect(annotations[0]).toContain('script test:unit');+ expect(annotations[0]).toContain(+ 'the run executed no test (collected 3: 2 skipped, 1 todo, 0 unfinished; 1 file)',+ );+ },+ BOUNDED_BY_CHILD_SILENCE,+ );++ test(+ 'a name filter that matches no test fails the same way and names the filter',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/filtered', ONE_EXECUTED);+ const run = await runVitest(signal, root, ['run', '-t', NO_TEST_NAMED], {+ GITHUB_ACTIONS: 'true',+ npm_lifecycle_event: 'test:unit',+ });+ expect(run.signal).toBeNull();+ expect(run.status, run.output).toBe(1);+ const annotations = errorAnnotations(run);+ expect(annotations, run.output).toHaveLength(1);+ expect(annotations[0]).toContain('@ok-fixture/filtered');+ expect(annotations[0]).toContain('script test:unit');+ expect(annotations[0]).toContain(+ `the run executed no test (collected 1: 1 skipped, 0 todo, 0 unfinished; 1 file; name filter /${NO_TEST_NAMED}/)`,+ );+ },+ BOUNDED_BY_CHILD_SILENCE,+ );++ test(+ 'a file filter that selects no file fails even when the caller passes --passWithNoTests',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/no-file', ONE_EXECUTED);+ const run = await runVitest(+ signal,+ root,+ ['run', '--passWithNoTests', 'no-fixture-file-is-named-this'],+ {+ GITHUB_ACTIONS: 'true',+ npm_lifecycle_event: 'test:unit',+ },+ );+ expect(run.signal).toBeNull();+ expect(run.output).toContain('No test files found, exiting with code 0');+ expect(run.status, run.output).toBe(1);+ const annotations = errorAnnotations(run);+ expect(annotations, run.output).toHaveLength(1);+ expect(annotations[0]).toContain(+ 'the run executed no test (collected 0: 0 skipped, 0 todo, 0 unfinished; 0 files)',+ );+ },+ BOUNDED_BY_CHILD_SILENCE,+ );++ test(+ 'a package with one executed test passes without an annotation',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/executed', ONE_EXECUTED);+ const run = await runVitest(signal, root, ['run'], {+ GITHUB_ACTIONS: 'true',+ npm_lifecycle_event: 'test:unit',+ });+ expect(run.signal).toBeNull();+ expect(run.status, run.output).toBe(0);+ expect(run.output).toContain('1 passed (1)');+ expect(errorAnnotations(run)).toEqual([]);+ },+ BOUNDED_BY_CHILD_SILENCE,+ );++ test(+ 'a run whose one executed test fails counts it as executed, so only the failure is annotated',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/failing', {+ 'failing.fixture.test.mjs':+ "test('asserts something false', () => { expect(1).toBe(2); });\n",+ });+ const run = await runVitest(signal, root, ['run'], {+ GITHUB_ACTIONS: 'true',+ npm_lifecycle_event: 'test:unit',+ });+ expect(run.signal).toBeNull();+ expect(run.status, run.output).toBe(1);+ expect(run.output).toContain('1 failed (1)');+ const annotations = errorAnnotations(run);+ expect(annotations, run.output).toHaveLength(1);+ expect(annotations[0]).toContain('title=failing.fixture.test.mjs > asserts something false');+ expect(annotations[0]).not.toContain('executed no test');+ },+ BOUNDED_BY_CHILD_SILENCE,+ );++ test(+ 'a run whose every file fails to import is red from the import failure alone, with no executed-no-test annotation',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/import-fails', IMPORT_FAILS);+ const run = await runVitest(signal, root, ['run'], {+ GITHUB_ACTIONS: 'true',+ npm_lifecycle_event: 'test:unit',+ });+ expect(run.signal).toBeNull();+ expect(run.status, run.output).toBe(1);+ expect(run.output).toContain('no-module-is-named-this.mjs');+ const annotations = errorAnnotations(run);+ expect(annotations, run.output).toHaveLength(1);+ expect(annotations[0]).toContain('import-fails.fixture.test.mjs');+ expect(annotations[0]).not.toContain('executed no test');+ },+ BOUNDED_BY_CHILD_SILENCE,+ );++ test(+ 'a run where one file fails to import and another skips every test still names the skips',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/import-fails-beside-skips', {+ ...IMPORT_FAILS,+ ...ALL_SKIP,+ });+ const run = await runVitest(signal, root, ['run'], {+ GITHUB_ACTIONS: 'true',+ npm_lifecycle_event: 'test:unit',+ });+ expect(run.signal).toBeNull();+ expect(run.status, run.output).toBe(1);+ const executedNothing = errorAnnotations(run).filter((line) =>+ line.includes('title=Vitest executed no test'),+ );+ expect(executedNothing, run.output).toHaveLength(1);+ expect(executedNothing[0]).toContain(+ 'the run executed no test (collected 3: 2 skipped, 1 todo, 0 unfinished; 2 files)',+ );+ },+ BOUNDED_BY_CHILD_SILENCE,+ );+});++describe('off GitHub Actions, the same runs end as before and each writes its report', () => {+ test(+ 'the all-skip, the filtered and the executed runs exit 0 and leave a Vitest JSON report of what ran',+ async ({ signal }) => {+ const allSkip = fixturePackage('@ok-fixture/all-skip', ALL_SKIP);+ const filtered = fixturePackage('@ok-fixture/filtered', ONE_EXECUTED);+ const ran = fixturePackage('@ok-fixture/executed', ONE_EXECUTED);+ const script = { npm_lifecycle_event: 'test:unit' };+ const runs = await Promise.all([+ runVitest(signal, allSkip, ['run'], script),+ runVitest(signal, filtered, ['run', '-t', NO_TEST_NAMED], script),+ runVitest(signal, ran, ['run'], script),+ ]);+ for (const run of runs) {+ expect(run.signal).toBeNull();+ expect(run.status, run.output).toBe(0);+ expect(errorAnnotations(run)).toEqual([]);+ }+ const reports = [allSkip, filtered, ran].map((root) =>+ readJson<VitestJsonReport>(join(root, 'test-results', 'vitest-test-unit.json')),+ );+ expect(+ reports.map(({ numTotalTests, numPassedTests, numPendingTests, numTodoTests }) => ({+ numTotalTests,+ numPassedTests,+ numPendingTests,+ numTodoTests,+ })),+ ).toEqual([+ { numTotalTests: 3, numPassedTests: 0, numPendingTests: 2, numTodoTests: 1 },+ { numTotalTests: 1, numPassedTests: 0, numPendingTests: 1, numTodoTests: 0 },+ { numTotalTests: 1, numPassedTests: 1, numPendingTests: 0, numTodoTests: 0 },+ ]);+ },+ BOUNDED_BY_CHILD_SILENCE,+ );+});++describe('each run names its report after the script that ran it and records where it came from', () => {+ test(+ 'a script run writes vitest-<script>.json with its colons mapped to hyphens, and its provenance beside it',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/provenance', ONE_EXECUTED);+ const run = await runVitest(signal, root, ['run'], {+ npm_lifecycle_event: 'test:integration:shard1',+ TURBO_HASH: 'f00dfeedcafe0123',+ GITHUB_RUN_ID: '4242',+ GITHUB_RUN_ATTEMPT: '2',+ GITHUB_JOB: 'test-shard',+ });+ expect(run.status, run.output).toBe(0);+ expect(reportDirectory(root)).toEqual([+ 'vitest-test-integration-shard1.json',+ 'vitest-test-integration-shard1.provenance.json',+ ]);+ expect(+ readJson(join(root, 'test-results', 'vitest-test-integration-shard1.provenance.json')),+ ).toEqual({+ report: 'vitest-test-integration-shard1.json',+ package: '@ok-fixture/provenance',+ script: 'test:integration:shard1',+ config: 'vitest.config.mjs',+ turboHash: 'f00dfeedcafe0123',+ runId: '4242',+ runAttempt: '2',+ job: 'test-shard',+ });+ const report = readJson<VitestJsonReport>(+ join(root, 'test-results', 'vitest-test-integration-shard1.json'),+ );+ expect(report.testResults.map(({ name }) => basename(name))).toEqual([+ 'executed.fixture.test.mjs',+ ]);+ },+ BOUNDED_BY_CHILD_SILENCE,+ );++ test(+ 'on GitHub Actions, two direct calls with no package script in one package write two distinct reports, each with its own provenance',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/direct', ONE_EXECUTED);+ const first = await runVitest(signal, root, ['run'], { GITHUB_ACTIONS: 'true' });+ const second = await runVitest(signal, root, ['run'], { GITHUB_ACTIONS: 'true' });+ expect(first.status, first.output).toBe(0);+ expect(second.status, second.output).toBe(0);+ const files = reportDirectory(root);+ const reports = files.filter((file) => !file.endsWith('.provenance.json'));+ expect(reports).toHaveLength(2);+ for (const report of reports) expect(report).toMatch(/^vitest-direct-.+\.json$/);+ expect(files).toEqual(+ reports.flatMap((report) => [report, report.replace(/\.json$/, '.provenance.json')]).sort(),+ );+ for (const report of reports) {+ expect(+ readJson(join(root, 'test-results', report.replace(/\.json$/, '.provenance.json'))),+ ).toEqual({+ report,+ package: '@ok-fixture/direct',+ script: null,+ config: 'vitest.config.mjs',+ turboHash: null,+ runId: null,+ runAttempt: null,+ job: null,+ });+ }+ },+ BOUNDED_BY_CHILD_SILENCE,+ );++ test(+ 'off GitHub Actions, a direct call with no package script writes no report, while a script run in the same package still does',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/direct-local', ONE_EXECUTED);+ const direct = await runVitest(signal, root, ['run'], {});+ expect(direct.status, direct.output).toBe(0);+ expect(direct.output).toContain('1 passed (1)');+ expect(reportDirectory(root)).toEqual([]);+ const scripted = await runVitest(signal, root, ['run'], { npm_lifecycle_event: 'test' });+ expect(scripted.status, scripted.output).toBe(0);+ expect(reportDirectory(root)).toEqual(['vitest-test.json', 'vitest-test.provenance.json']);+ },+ BOUNDED_BY_CHILD_SILENCE,+ );+});++function nestedRunFixture(innerRoot: string): string {+ return [+ "import { spawnSync } from 'node:child_process';",+ "import { existsSync } from 'node:fs';",+ "import { join } from 'node:path';",+ `const INNER = ${JSON.stringify(innerRoot)};`,+ "test('an all-skip Vitest run started from this test inherits GitHub Actions and still passes, writing no report', () => {",+ ` const inner = spawnSync(process.execPath, [${JSON.stringify(VITEST_CLI)}, 'run'], { cwd: INNER, env: process.env, encoding: 'utf8', timeout: ${CHILD_SILENCE_BOUND_MS / 2} });`,+ " expect(process.env.GITHUB_ACTIONS).toBe('true');",+ " expect(inner.status, inner.stdout + '\\n' + inner.stderr).toBe(0);",+ " expect(existsSync(join(INNER, 'test-results'))).toBe(false);",+ '});',+ '',+ ].join('\n');+}++function projectsConfig(names: string[]): string {+ return [+ `import { okVitestBase } from ${JSON.stringify(BASE_MODULE)};`,+ 'const project = (name) => ({',+ ' ...okVitestBase,',+ " test: { ...okVitestBase.test, globals: true, name, include: [name + '/*.fixture.test.mjs'] },",+ '});',+ `export default { test: { projects: ${JSON.stringify(names)}.map(project) } };`,+ '',+ ].join('\n');+}++const OWN_JSON_REPORTER_CONFIG = [+ `import { okVitestBase } from ${JSON.stringify(BASE_MODULE)};`,+ 'export default {',+ ' ...okVitestBase,',+ ' test: {',+ ' ...okVitestBase.test,',+ ' globals: true,',+ " include: ['*.fixture.test.mjs'],",+ " reporters: ['default', 'json'],",+ " outputFile: { json: 'test-results/own-report.json' },",+ ' },',+ '};',+ '',+].join('\n');++describe('only the outermost Vitest run applies the floor and writes a report', () => {+ test(+ 'a Vitest run a test starts inherits the outer run, so it applies no floor and writes no report while the outer run keeps both',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/outer', {});+ const inner = join(root, 'inner');+ mkdirSync(inner);+ writePackage(inner, '@ok-fixture/inner', ALL_SKIP, BASE_CONFIG);+ writeFileSync(join(root, 'nested.fixture.test.mjs'), nestedRunFixture(inner));+ const run = await runVitest(signal, root, ['run'], {+ GITHUB_ACTIONS: 'true',+ npm_lifecycle_event: 'test:unit',+ });+ expect(run.signal).toBeNull();+ expect(run.status, run.output).toBe(0);+ expect(errorAnnotations(run)).toEqual([]);+ expect(reportDirectory(root)).toEqual([+ 'vitest-test-unit.json',+ 'vitest-test-unit.provenance.json',+ ]);+ expect(reportDirectory(inner)).toEqual([]);+ },+ BOUNDED_BY_CHILD_SILENCE,+ );++ test(+ 'a run whose projects each carry the plugin, as the uncached tier does, writes one report and applies the floor once',+ async ({ signal }) => {+ const root = fixturePackage(+ '@ok-fixture/projects',+ {+ 'first/all-skip.fixture.test.mjs': ALL_SKIP['all-skip.fixture.test.mjs'],+ 'second/all-skip.fixture.test.mjs': ALL_SKIP['all-skip.fixture.test.mjs'],+ },+ projectsConfig(['first', 'second']),+ );+ const run = await runVitest(signal, root, ['run'], {+ GITHUB_ACTIONS: 'true',+ npm_lifecycle_event: 'test:uncached',+ });+ expect(run.signal).toBeNull();+ expect(run.status, run.output).toBe(1);+ const annotations = errorAnnotations(run);+ expect(annotations, run.output).toHaveLength(1);+ expect(annotations[0]).toContain(+ 'the run executed no test (collected 6: 4 skipped, 2 todo, 0 unfinished; 2 files)',+ );+ expect(reportDirectory(root)).toEqual([+ 'vitest-test-uncached.json',+ 'vitest-test-uncached.provenance.json',+ ]);+ expect(+ readJson<VitestJsonReport>(join(root, 'test-results', 'vitest-test-uncached.json'))+ .numTotalTests,+ ).toBe(6);+ },+ BOUNDED_BY_CHILD_SILENCE,+ );++ test(+ 'vitest list executes nothing by design, so on GitHub Actions it stays green and writes no report',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/list', ALL_SKIP);+ const run = await runVitest(signal, root, ['list'], {+ GITHUB_ACTIONS: 'true',+ npm_lifecycle_event: 'test:unit',+ });+ expect(run.signal).toBeNull();+ expect(run.status, run.output).toBe(0);+ expect(run.output).toContain('skips itself at runtime');+ expect(errorAnnotations(run)).toEqual([]);+ expect(reportDirectory(root)).toEqual([]);+ },+ BOUNDED_BY_CHILD_SILENCE,+ );+});++describe('the report and the floor sit beside the configured reporters', () => {+ test(+ 'a config that writes its own JSON report still writes it, and the run report lands beside it',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/own-report', ONE_EXECUTED, OWN_JSON_REPORTER_CONFIG);+ const run = await runVitest(signal, root, ['run'], { npm_lifecycle_event: 'test:node' });+ expect(run.status, run.output).toBe(0);+ expect(reportDirectory(root)).toEqual([+ 'own-report.json',+ 'vitest-test-node.json',+ 'vitest-test-node.provenance.json',+ ]);+ for (const file of ['own-report.json', 'vitest-test-node.json']) {+ expect(+ readJson<VitestJsonReport>(join(root, 'test-results', file)).testResults.map(({ name }) =>+ basename(name),+ ),+ ).toEqual(['executed.fixture.test.mjs']);+ }+ },+ BOUNDED_BY_CHILD_SILENCE,+ );++ test(+ 'a --reporter flag replaces the configured reporters but drops neither the report nor the floor',+ async ({ signal }) => {+ const root = fixturePackage('@ok-fixture/reporter-flag', ALL_SKIP);+ const run = await runVitest(signal, root, ['run', '--reporter=dot'], {+ GITHUB_ACTIONS: 'true',+ npm_lifecycle_event: 'test:unit',+ });+ expect(run.signal).toBeNull();+ expect(run.status, run.output).toBe(1);+ expect(errorAnnotations(run), run.output).toHaveLength(1);+ expect(reportDirectory(root)).toEqual([+ 'vitest-test-unit.json',+ 'vitest-test-unit.provenance.json',+ ]);+ },+ BOUNDED_BY_CHILD_SILENCE,+ );+});diff --git a/test-support/vitest-run-evidence.ts b/test-support/vitest-run-evidence.tsnew file mode 100644index 000000000..bdb9c10ec--- /dev/null+++ b/test-support/vitest-run-evidence.ts@@ -0,0 +1,139 @@+/* biome-ignore-all lint/suspicious/noUndeclaredEnvVars: Turbo passes GITHUB_* and TURBO_HASH to a task without hashing them, and npm_lifecycle_event is the task's own script, so none of them belongs in a task key. */+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname, join, relative, sep } from 'node:path';+import type { Plugin } from 'vitest/config';+import type { Reporter, TestCase, VitestPluginContext } from 'vitest/node';+import { executed, sumAcrossFiles, tallyVitestRun, type VitestFileTally } from './vitest-run-tally';++export const VITEST_RUN_EVIDENCE_OWNER_ENV = 'OK_VITEST_RUN_EVIDENCE_OWNER';++type Vitest = VitestPluginContext['vitest'];++type RunIdentity = { package: string | null; script: string | null; config: string | null };++function nearestPackageName(start: string): string | null {+ for (let dir = start; ; dir = dirname(dir)) {+ const manifest = join(dir, 'package.json');+ if (existsSync(manifest)) {+ const { name } = JSON.parse(readFileSync(manifest, 'utf8')) as { name?: unknown };+ return typeof name === 'string' ? name : null;+ }+ if (dirname(dir) === dir) return null;+ }+}++function runIdentity(vitest: Vitest, script: string | null): RunIdentity {+ const { root } = vitest.config;+ const configFile = vitest.vite.config.configFile;+ return {+ package: nearestPackageName(root),+ script,+ config: configFile === undefined ? null : relative(root, configFile).split(sep).join('/'),+ };+}++function escapeData(text: string): string {+ return text.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A');+}++function plural(count: number, noun: string): string {+ return `${count} ${noun}${count === 1 ? '' : 's'}`;+}++function emptyRunAnnotation(+ identity: RunIdentity,+ files: ReadonlyArray<VitestFileTally>,+ root: string,+ testNamePattern: RegExp | undefined,+): string {+ const skipped = sumAcrossFiles(files, (file) => file.skipped);+ const todo = sumAcrossFiles(files, (file) => file.todo);+ const unfinished = sumAcrossFiles(files, (file) => file.unfinished);+ const stopped = sumAcrossFiles(files, (file) => file.stopped);+ const collected = skipped + todo + unfinished + stopped;+ const subject = [+ identity.package ?? `the package at ${root}`,+ identity.script === null ? 'no package script' : `script ${identity.script}`,+ identity.config === null ? 'no config file' : `config ${identity.config}`,+ ].join(', ');+ const counts = [+ `${skipped} skipped, ${todo} todo, ${unfinished} unfinished`,+ ...(stopped > 0 ? [`${stopped} stopped by a failure`] : []),+ ].join(', ');+ const scope = [+ plural(files.length, 'file'),+ ...(testNamePattern === undefined ? [] : [`name filter ${String(testNamePattern)}`]),+ ].join('; ');+ const message = `${subject}: the run executed no test (collected ${collected}: ${counts}; ${scope}). On GitHub Actions a Vitest run must execute a test; make it execute one, or correct the filter or skip that emptied it.`;+ return `::error title=Vitest executed no test::${escapeData(message)}`;+}++type RunEvidenceFiles = { directory: string; report: string; provenance: string };++function runEvidenceFiles(root: string, script: string | null): RunEvidenceFiles {+ const name =+ script === null ? `vitest-direct-${randomUUID()}` : `vitest-${script.replaceAll(':', '-')}`;+ return {+ directory: join(root, 'test-results'),+ report: `${name}.json`,+ provenance: `${name}.provenance.json`,+ };+}++function writeProvenance(files: RunEvidenceFiles, identity: RunIdentity): void {+ const provenance = {+ report: files.report,+ ...identity,+ turboHash: process.env.TURBO_HASH ?? null,+ runId: process.env.GITHUB_RUN_ID ?? null,+ runAttempt: process.env.GITHUB_RUN_ATTEMPT ?? null,+ job: process.env.GITHUB_JOB ?? null,+ };+ mkdirSync(files.directory, { recursive: true });+ writeFileSync(+ join(files.directory, files.provenance),+ `${JSON.stringify(provenance, null, 2)}\n`,+ );+}++function evidenceReporter(+ vitest: Vitest,+ script: string | null,+ evidence: RunEvidenceFiles,+): Reporter {+ const started = new WeakSet<TestCase>();+ return {+ onTestCaseReady(testCase) {+ started.add(testCase);+ },+ onTestRunEnd(testModules) {+ const identity = runIdentity(vitest, script);+ writeProvenance(evidence, identity);+ if (process.env.GITHUB_ACTIONS !== 'true') return;+ const { root, testNamePattern } = vitest.config;+ const files = tallyVitestRun(testModules, root, started);+ if (sumAcrossFiles(files, executed) > 0) return;+ process.exitCode = 1;+ if (files.length > 0 && files.every((file) => file.failedDuringCollection)) return;+ vitest.logger.log(`\n${emptyRunAnnotation(identity, files, root, testNamePattern)}`);+ },+ };+}++export function vitestRunEvidence(): Plugin {+ return {+ name: 'ok:vitest-run-evidence',+ configureVitest({ vitest }) {+ if (process.env[VITEST_RUN_EVIDENCE_OWNER_ENV] !== undefined) return;+ process.env[VITEST_RUN_EVIDENCE_OWNER_ENV] = String(process.pid);+ const script = process.env.npm_lifecycle_event || null;+ if (script === null && process.env.GITHUB_ACTIONS !== 'true') return;+ const evidence = runEvidenceFiles(vitest.config.root, script);+ vitest.config.reporters.push(+ ['json', { outputFile: join(evidence.directory, evidence.report) }],+ evidenceReporter(vitest, script, evidence),+ );+ },+ };+}diff --git a/test-support/vitest-run-tally.ts b/test-support/vitest-run-tally.tsnew file mode 100644index 000000000..0260df4cd--- /dev/null+++ b/test-support/vitest-run-tally.ts@@ -0,0 +1,81 @@+import { relative, sep } from 'node:path';+import type { TestCase, TestModule, TestSuite } from 'vitest/node';++export type VitestFileTally = {+ path: string;+ passed: number;+ failed: number;+ skipped: number;+ todo: number;+ unfinished: number;+ stopped: number;+ emptySkippedSuites: string[];+ emptyStoppedSuites: string[];+ failedDuringCollection: boolean;+};++function failedWithOwnError(entity: TestSuite | TestModule): boolean {+ return entity.state() === 'failed' && entity.errors().length > 0;+}++function stoppedByFailure(entity: TestCase | TestSuite): boolean {+ if (entity.options.mode !== 'run') return false;+ let enclosing: TestSuite | TestModule = entity.parent;+ while (!failedWithOwnError(enclosing)) {+ if (enclosing.type === 'module') return false;+ enclosing = enclosing.parent;+ }+ return true;+}++export function tallyVitestRun(+ testModules: ReadonlyArray<TestModule>,+ root: string,+ started: WeakSet<TestCase>,+): VitestFileTally[] {+ return testModules.map((testModule) => {+ const tally: VitestFileTally = {+ path: relative(root, testModule.moduleId).split(sep).join('/'),+ passed: 0,+ failed: 0,+ skipped: 0,+ todo: 0,+ unfinished: 0,+ stopped: 0,+ emptySkippedSuites: [],+ emptyStoppedSuites: [],+ failedDuringCollection: false,+ };+ for (const test of testModule.children.allTests()) {+ const { state } = test.result();+ if (state === 'passed') tally.passed += 1;+ else if (state === 'failed') tally.failed += 1;+ else if (state === 'pending') tally.unfinished += 1;+ else if (state !== 'skipped') {+ throw new Error(`test "${test.fullName}" in ${tally.path} reports an unknown state`);+ } else if (test.options.mode === 'todo') tally.todo += 1;+ else if (!started.has(test) && stoppedByFailure(test)) tally.stopped += 1;+ else tally.skipped += 1;+ }+ for (const suite of testModule.children.allSuites()) {+ if (suite.state() === 'skipped' && suite.children.allTests().next().done) {+ if (stoppedByFailure(suite)) tally.emptyStoppedSuites.push(suite.fullName);+ else tally.emptySkippedSuites.push(suite.fullName);+ }+ }+ tally.failedDuringCollection =+ failedWithOwnError(testModule) && testModule.diagnostic().collectDuration === 0;+ return tally;+ });+}++export function executed(file: VitestFileTally): number {+ return file.passed + file.failed;+}++export function sumAcrossFiles(+ files: ReadonlyArray<VitestFileTally>,+ count: (file: VitestFileTally) => number,+): number {+ return files.reduce((total, file) => total + count(file), 0);+}diff --git a/test-support/vitest.base.ts b/test-support/vitest.base.tsindex 0474a3f6c..1b9626da2 100644--- a/test-support/vitest.base.ts+++ b/test-support/vitest.base.ts@@ -2,6 +2,7 @@ import { availableParallelism } from 'node:os';import { fileURLToPath } from 'node:url';import { configDefaults, type Plugin, type ViteUserConfig } from 'vitest/config';import { UNCACHED_TEST_GLOBS } from './uncached-tier';+import { vitestRunEvidence } from './vitest-run-evidence';const cpuCount = availableParallelism();const boundedMaxForks =@@ -25,7 +26,7 @@ const bunGlobalShimPath = fileURLToPath(new URL('./bun-global-shim.ts', import.mconst noNetConnectPath = fileURLToPath(new URL('./no-net-connect.ts', import.meta.url));export const okVitestBase = {- plugins: [importMetaDirPlugin],+ plugins: [importMetaDirPlugin, vitestRunEvidence()],resolve: {conditions: ['development'],},diff --git a/turbo.json b/turbo.jsonindex 9e3d0f515..e0b5882b9 100644--- a/turbo.json+++ b/turbo.json@@ -112,12 +112,19 @@"test": {"dependsOn": ["^build"],"cache": true,- "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**"]+ "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**"],+ "outputs": ["test-results/vitest-test.json", "test-results/vitest-test.provenance.json"]},"@inkeep/open-knowledge-docs#test": {"dependsOn": ["^build", "build"],"cache": true,- "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**"]+ "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**"],+ "outputs": [+ "test-results/vitest-test.json",+ "test-results/vitest-test.provenance.json",+ "test-results/vitest-test-real-source.json",+ "test-results/vitest-test-real-source.provenance.json"+ ]},"@inkeep/open-knowledge-server#test": {"dependsOn": ["^build"],@@ -129,7 +136,8 @@"../../test-support/*.ts","../../test-support/test-only-source-file.mjs","../app/src/editor/observers.ts"- ]+ ],+ "outputs": ["test-results/vitest-test.json", "test-results/vitest-test.provenance.json"]},"@inkeep/open-knowledge#test": {"dependsOn": ["^build", "build"],@@ -138,7 +146,8 @@"$TURBO_DEFAULT$","$TURBO_ROOT$/test-support/**","$TURBO_ROOT$/scripts/read-jsonc.mjs"- ]+ ],+ "outputs": ["test-results/vitest-test.json", "test-results/vitest-test.provenance.json"]},"@inkeep/open-knowledge-desktop#test": {"dependsOn": ["^build"],@@ -159,17 +168,20 @@"../app/*.html","../app/src/**","!../app/src/**/*.md"- ]+ ],+ "outputs": ["test-results/vitest-test.json", "test-results/vitest-test.provenance.json"]},"@inkeep/md-conformance#test": {"dependsOn": ["^build"],"cache": true,- "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**", "../server/src/**/*.ts"]+ "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**", "../server/src/**/*.ts"],+ "outputs": ["test-results/vitest-test.json", "test-results/vitest-test.provenance.json"]},"@inkeep/open-knowledge-core#test": {"dependsOn": ["^build"],"cache": true,- "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**"]+ "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**"],+ "outputs": ["test-results/vitest-test.json", "test-results/vitest-test.provenance.json"]},"test:dom": {"dependsOn": ["^build"],@@ -182,6 +194,10 @@"../md-conformance/src/**/*.ts","../md-conformance/src/**/*.json","../md-conformance/corpora/typed-view-scripts.json"+ ],+ "outputs": [+ "test-results/vitest-test-dom.json",+ "test-results/vitest-test-dom.provenance.json"]},"test:browser": {@@ -208,6 +224,10 @@"$TURBO_ROOT$/lint-plugins/no-comments/**","$TURBO_ROOT$/packages/cli/src/**","$TURBO_ROOT$/packages/cli/package.json"+ ],+ "outputs": [+ "test-results/vitest-test-integration.json",+ "test-results/vitest-test-integration.provenance.json"]},"test:integration:shard1": {@@ -221,6 +241,10 @@"$TURBO_ROOT$/lint-plugins/no-comments/**","$TURBO_ROOT$/packages/cli/src/**","$TURBO_ROOT$/packages/cli/package.json"+ ],+ "outputs": [+ "test-results/vitest-test-integration-shard1.json",+ "test-results/vitest-test-integration-shard1.provenance.json"]},"test:integration:shard2": {@@ -234,6 +258,10 @@"$TURBO_ROOT$/lint-plugins/no-comments/**","$TURBO_ROOT$/packages/cli/src/**","$TURBO_ROOT$/packages/cli/package.json"+ ],+ "outputs": [+ "test-results/vitest-test-integration-shard2.json",+ "test-results/vitest-test-integration-shard2.provenance.json"]},"test:integration:shard3": {@@ -247,6 +275,10 @@"$TURBO_ROOT$/lint-plugins/no-comments/**","$TURBO_ROOT$/packages/cli/src/**","$TURBO_ROOT$/packages/cli/package.json"+ ],+ "outputs": [+ "test-results/vitest-test-integration-shard3.json",+ "test-results/vitest-test-integration-shard3.provenance.json"]},"test:conversion": {@@ -257,6 +289,10 @@"$TURBO_ROOT$/test-support/**","../core/src/**/*.ts","../server/src/**/*.ts"+ ],+ "outputs": [+ "test-results/vitest-test-conversion.json",+ "test-results/vitest-test-conversion.provenance.json"]},"test:e2e": {@@ -307,7 +343,11 @@"test:perf:regression:unit": {"dependsOn": [],"cache": true,- "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**"]+ "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**"],+ "outputs": [+ "test-results/vitest-test-perf-regression-unit.json",+ "test-results/vitest-test-perf-regression-unit.provenance.json"+ ]},"test:perf:regression": {"dependsOn": [],@@ -325,7 +365,11 @@"test:health:unit": {"dependsOn": [],"cache": true,- "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**"]+ "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/test-support/**"],+ "outputs": [+ "test-results/vitest-test-health-unit.json",+ "test-results/vitest-test-health-unit.provenance.json"+ ]},"test:health": {"dependsOn": [],