diff --git a/client/CLAUDE.md b/client/CLAUDE.md index 2c0a88345..d03d8affa 100644 --- a/client/CLAUDE.md +++ b/client/CLAUDE.md @@ -16,6 +16,7 @@ npm run lint:size # no source file or stylesheet past 1000 lines, no tes npm run lint:format # Prettier: every file outside scripts/format-baseline.json must be formatted, the list only shrinks (CI gate; npx prettier --write , then --update) npm run lint:layers # imports go downwards: components never import pages/ or mobile/, nothing under the views imports a view; per-file counts may only shrink (CI gate; --list, --update) npm run lint:offline # no view file (components/mobile/pages/hooks) imports src/api/ beyond scripts/offline-baseline.json, which only shrinks (CI gate; --list, --update) +npm run lint:skips # no .only anywhere; skipped/todo tests per file may only shrink against scripts/skip-baseline.json (CI gate; skipIf/runIf are fine) npm run test # vitest run (tests/** + co-located src/**/*.test.{ts,tsx}); also test:unit / test:integration / test:coverage npm run e2e # Playwright (CI runs --project=public --project=app; e2e:report opens the last report) npm run shots # Playwright screenshot project (shots:promote to accept) diff --git a/client/package.json b/client/package.json index 643d5e044..41266417c 100644 --- a/client/package.json +++ b/client/package.json @@ -24,6 +24,7 @@ "lint:format": "node scripts/format-lint.mjs", "lint:layers": "node scripts/layer-lint.mjs", "lint:offline": "node scripts/offline-lint.mjs", + "lint:skips": "node scripts/skip-lint.mjs", "check:gl-split": "node scripts/check-gl-split.mjs", "theme:lint": "node scripts/theme-lint.mjs", "theme:lint:strict": "node scripts/theme-lint.mjs --strict", diff --git a/client/scripts/lib/skips.mjs b/client/scripts/lib/skips.mjs new file mode 100644 index 000000000..56864dc2b --- /dev/null +++ b/client/scripts/lib/skips.mjs @@ -0,0 +1,113 @@ +/* + * The matching and the comparison behind lint:skips (scripts/skip-lint.mjs). + */ +import { join } from 'node:path' +import ts from 'typescript' +import { countMap, listFiles, lowerCounts, readBaseline, readText, TEST_FILE, toKey, writeBaseline } from './ratchet.mjs' + +/** The test functions of vitest and Playwright a modifier can hang off. */ +const RUNNERS = new Set(['it', 'test', 'describe', 'suite', 'bench']) +/** The jasmine-style shorthands vitest also knows. */ +const SHORTHAND = new Set(['xit', 'xtest', 'xdescribe']) + +export const DIRS = ['src', 'tests', 'e2e'] + +const accepts = (key) => + /\.tsx?$/.test(key) && (key.startsWith('src/') ? TEST_FILE.test(key) : true) + +/** The identifier a chain like test.describe.skip.each starts from. */ +function rootOf(node) { + while (ts.isPropertyAccessExpression(node) || ts.isCallExpression(node)) node = node.expression + return ts.isIdentifier(node) ? node.text : null +} + +const isTitle = (node) => Boolean(node) && (ts.isStringLiteralLike(node) || ts.isTemplateExpression(node)) + +/** + * The tests a file switches off or narrows down, as `line: code`. + * + * skipped: it.skip / describe.skip / test.todo and the x-shorthands, each + * declaring a test that never runs. A skip with a condition first + * (Playwright's test.skip(!seed.id, 'why'), or called bare inside a test) + * decides at run time and is no declaration; neither are skipIf and runIf. + * + * only: .only anywhere, which silently drops every other test in the file. + */ +export function modifiers(source, file) { + const kind = file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS + const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, kind) + const skipped = [] + const only = [] + const at = (node) => `${sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1}: ${node.getText(sf).slice(0, 60)}` + const visit = (node) => { + if (ts.isPropertyAccessExpression(node) && RUNNERS.has(rootOf(node.expression) ?? '')) { + const name = node.name.text + if (name === 'only') only.push(at(node)) + else if (name === 'todo') skipped.push(at(node)) + else if (name === 'skip') { + const call = ts.isCallExpression(node.parent) && node.parent.expression === node ? node.parent : null + // test.skip.each(table)(...) declares skipped tests; test.skip('title', fn) declares one. + if (!call || isTitle(call.arguments[0])) skipped.push(at(node)) + } + } else if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && SHORTHAND.has(node.expression.text)) { + skipped.push(at(node.expression)) + } + ts.forEachChild(node, visit) + } + visit(sf) + return { skipped, only } +} + +/** The skipped and focused tests per file under src/, tests/ and e2e/, keyed by the path from root. */ +export function scan(root) { + const skipped = {} + const only = {} + for (const path of listFiles(root, DIRS, accepts)) { + const found = modifiers(readText(path), path) + const key = toKey(root, path) + if (found.skipped.length) skipped[key] = found.skipped + if (found.only.length) only[key] = found.only + } + return { skipped, only } +} + +/** + * Runs the check: no .only anywhere, and no file with more skipped tests than + * its entry in the baseline at baselinePath. Returns the exit code. + */ +export function check({ + root, + baselinePath = join(root, 'scripts/skip-baseline.json'), + update = false, + log = console.log, + error = console.error, +}) { + const { skipped, only } = scan(root) + const counts = Object.fromEntries(Object.entries(skipped).map(([key, list]) => [key, list.length])) + let baseline = readBaseline(baselinePath, countMap) + + if (update) { + baseline = lowerCounts(baseline, counts) + writeBaseline(baselinePath, baseline) + } + + for (const [key, list] of Object.entries(only)) { + error(`FAIL ${key}: .only runs this test alone and drops every other one in the file:`) + for (const line of list) error(` ${line}`) + } + const grown = Object.entries(counts).filter(([key, n]) => n > (baseline[key] ?? 0)) + for (const [key, n] of grown) { + error(`FAIL ${key}: ${n} skipped or todo test(s), baseline ${baseline[key] ?? 0}:`) + for (const line of skipped[key]) error(` ${line}`) + } + if (grown.length) { + error( + 'Fix the test, delete it if its feature is gone, or use skipIf/runIf when it depends on the environment.', + ) + } + const lowerable = Object.entries(baseline).filter(([key, n]) => (counts[key] ?? 0) < n) + if (lowerable.length && !update) log(`${lowerable.length} file(s) skip fewer tests than the baseline: run with --update to lower it.`) + const sum = (map) => Object.values(map).reduce((a, b) => a + b, 0) + log(`skips: ${sum(counts)} skipped or todo test(s), baseline allows ${sum(baseline)}; ${Object.keys(only).length} file(s) with .only`) + return grown.length || Object.keys(only).length ? 1 : 0 +} diff --git a/client/scripts/skip-baseline.json b/client/scripts/skip-baseline.json new file mode 100644 index 000000000..59d86e2a4 --- /dev/null +++ b/client/scripts/skip-baseline.json @@ -0,0 +1,3 @@ +{ + "src/pages/JourneyDetailPage.test.tsx": 35 +} diff --git a/client/scripts/skip-lint.mjs b/client/scripts/skip-lint.mjs new file mode 100644 index 000000000..9396fd5f8 --- /dev/null +++ b/client/scripts/skip-lint.mjs @@ -0,0 +1,23 @@ +#!/usr/bin/env node +/* + * lint:skips: no test is focused, and skipped tests may only go away. + * + * A stray .only passes CI while the rest of its file never runs, so it fails + * this check wherever it appears. A skipped or todo test is coverage that was + * switched off and then forgotten (JourneyDetailPage.test.tsx has carried 35 + * skipped blocks since April); the files that hold some are listed in + * scripts/skip-baseline.json with their count, and a file may hold no more. + * A skip that decides at run time (skipIf, runIf, Playwright's + * test.skip(condition, 'why')) is not counted. Covers the vitest tests under + * src/ and tests/ and the Playwright specs under e2e/. + * + * npm run lint:skips check against the baseline (CI) + * npm run lint:skips -- --update lower the baseline to what the files hold now; + * it never raises an entry + */ +import { fileURLToPath } from 'node:url' +import { runCli } from './lib/ratchet.mjs' +import { check } from './lib/skips.mjs' + +const root = fileURLToPath(new URL('..', import.meta.url)) +await runCli('lint:skips', (args) => check({ root, update: args.includes('--update') })) diff --git a/client/tests/unit/scripts/skip-lint.test.ts b/client/tests/unit/scripts/skip-lint.test.ts new file mode 100644 index 000000000..115580bb1 --- /dev/null +++ b/client/tests/unit/scripts/skip-lint.test.ts @@ -0,0 +1,100 @@ +import { readFileSync } from 'node:fs'; +import { afterEach, describe, expect, it } from 'vitest'; +import { RatchetError } from '../../../scripts/lib/ratchet.mjs'; +import { check, modifiers } from '../../../scripts/lib/skips.mjs'; +import { ratchetTree, type RatchetTree } from '../../helpers/ratchetFixture'; + +let tree: RatchetTree; +afterEach(() => tree?.remove()); + +const BASELINE = 'scripts/skip-baseline.json'; +const PASSING = "it('works', () => {})\n"; + +function run(baseline: Record, files: Record, update = false) { + tree = ratchetTree({ + [BASELINE]: JSON.stringify(baseline), + 'src/a.test.ts': PASSING, + 'tests/b.test.ts': PASSING, + 'e2e/c.spec.ts': PASSING, + ...files, + }); + return check({ root: tree.root, baselinePath: tree.path(BASELINE), update, ...tree.out }); +} + +describe('lint:skips', () => { + it('SKIPS-001: finds declared skips, todos and the x-shorthands', () => { + const source = [ + "it.skip('a', () => {})", + "describe.skip('b', () => {})", + "test.todo('c')", + "it.skip.each([1])('d %s', () => {})", + "test.describe.skip('e', () => {})", + "xit('f', () => {})", + "it.concurrent.skip('g', () => {})", + ].join('\n'); + expect(modifiers(source, 'x.test.ts').skipped.map((s: string) => s.split(':')[0])).toEqual([ + '1', + '2', + '3', + '4', + '5', + '6', + '7', + ]); + }); + + it('SKIPS-002: leaves run-time skips, skipIf/runIf, comments and strings alone', () => { + const source = [ + "test.skip(!seed.collectionId, 'collections addon unavailable')", + "test('x', async () => { test.skip() })", + "it.skipIf(process.platform === 'win32')('y', () => {})", + "describe.runIf(hasS3)('z', () => {})", + "// it.skip('commented out', () => {})", + 'const doc = "describe.only(\'in a string\')"', + 'ctx.skip()', + ].join('\n'); + expect(modifiers(source, 'x.test.ts')).toEqual({ skipped: [], only: [] }); + }); + + it('SKIPS-003: finds .only on any runner', () => { + const source = "it.only('a', () => {})\ndescribe.only('b', () => {})\ntest.describe.only('c', () => {})\n"; + expect(modifiers(source, 'x.spec.ts').only).toHaveLength(3); + }); + + it('SKIPS-004: fails any .only, even in a file with a baseline entry', () => { + expect(run({ 'tests/b.test.ts': 5 }, { 'tests/b.test.ts': "it.only('a', () => {})\n" })).toBe(1); + expect(tree.error.join('\n')).toMatch(/tests\/b\.test\.ts: \.only runs this test alone/); + tree.remove(); + expect(run({}, { 'e2e/c.spec.ts': "test.only('a', async () => {})\n" })).toBe(1); + }); + + it('SKIPS-005: fails a new skip and holds a baselined file at its entry', () => { + expect(run({}, { 'src/a.test.ts': "it.skip('a', () => {})\n" })).toBe(1); + expect(tree.error.join('\n')).toMatch(/src\/a\.test\.ts: 1 skipped or todo test\(s\), baseline 0/); + tree.remove(); + expect(run({ 'src/a.test.ts': 1 }, { 'src/a.test.ts': "it.skip('a', () => {})\n" })).toBe(0); + }); + + it('SKIPS-006: only scans test files under src/', () => { + expect(run({}, { 'src/helper.ts': "it.skip('not a test file', () => {})\n" })).toBe(0); + }); + + it('SKIPS-007: --update lowers the baseline and never raises it', () => { + run( + { 'src/a.test.ts': 3, 'tests/b.test.ts': 1 }, + { 'src/a.test.ts': "it.skip('a', () => {})\nit.skip('b', () => {})\n" }, + true + ); + expect(JSON.parse(readFileSync(tree.path(BASELINE), 'utf8'))).toEqual({ 'src/a.test.ts': 2 }); + }); + + it('SKIPS-008: a missing baseline or test directory stops the check', () => { + tree = ratchetTree({ 'src/a.test.ts': PASSING, 'tests/b.test.ts': PASSING, 'e2e/c.spec.ts': PASSING }); + expect(() => check({ root: tree.root, baselinePath: tree.path(BASELINE), ...tree.out })).toThrow(RatchetError); + tree.remove(); + tree = ratchetTree({ [BASELINE]: '{}', 'src/a.test.ts': PASSING, 'tests/b.test.ts': PASSING }); + expect(() => check({ root: tree.root, baselinePath: tree.path(BASELINE), ...tree.out })).toThrow( + /e2e\/ does not exist/ + ); + }); +});