test-inventory 0.9.1 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ import schema from '../schema/v1.json' with { type: 'json' };
2
+ import { OptionsError } from "./options.js";
3
+ const definitions = schema.definitions;
4
+ /** Checks the published inventory format without running code from the saved file. */
5
+ function matches(value, rule) {
6
+ if (rule.$ref)
7
+ return matches(value, definitions[rule.$ref.slice('#/definitions/'.length)]);
8
+ if (Array.isArray(rule.type))
9
+ return rule.type.some((type) => matches(value, { ...rule, type }));
10
+ if (rule.anyOf)
11
+ return rule.anyOf.some((option) => matches(value, option));
12
+ if ('const' in rule && value !== rule.const)
13
+ return false;
14
+ if (rule.enum && !rule.enum.includes(value))
15
+ return false;
16
+ if (rule.type === 'null')
17
+ return value === null;
18
+ if (rule.type === 'string')
19
+ return typeof value === 'string' && (!rule.pattern || new RegExp(rule.pattern).test(value));
20
+ if (rule.type === 'boolean')
21
+ return typeof value === 'boolean';
22
+ if (rule.type === 'number' || rule.type === 'integer') {
23
+ return (typeof value === 'number' &&
24
+ Number.isFinite(value) &&
25
+ (rule.type !== 'integer' || Number.isInteger(value)) &&
26
+ (rule.minimum === undefined || value >= rule.minimum));
27
+ }
28
+ if (rule.type === 'array')
29
+ return Array.isArray(value) && value.every((item) => matches(item, rule.items));
30
+ {
31
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
32
+ return false;
33
+ const object = value;
34
+ if (rule.required?.some((key) => !Object.hasOwn(object, key)))
35
+ return false;
36
+ return Object.entries(object).every(([key, item]) => {
37
+ const property = rule.properties && Object.hasOwn(rule.properties, key) ? rule.properties[key] : undefined;
38
+ if (property)
39
+ return matches(item, property);
40
+ return typeof rule.additionalProperties === 'object'
41
+ ? matches(item, rule.additionalProperties)
42
+ : rule.additionalProperties !== false;
43
+ });
44
+ }
45
+ }
46
+ /** Validates a saved scan before a diff reads its records; projected records and JSON Lines are not full scans. */
47
+ export function checkInventory(value, name) {
48
+ let valid = false;
49
+ try {
50
+ JSON.stringify(value);
51
+ valid = matches(value, schema);
52
+ }
53
+ catch {
54
+ // Cyclic objects and excessively deep metadata are not saved inventories.
55
+ }
56
+ if (!valid)
57
+ throw new OptionsError(`${name} must be a complete schema v1 JSON inventory, without --fields or --format jsonl.`);
58
+ const inventory = value;
59
+ const ids = new Set(inventory.tests.map((test) => test.id));
60
+ if (ids.size !== inventory.tests.length)
61
+ throw new OptionsError(`${name} contains duplicate test ids. Scan it again without combining inventories.`);
62
+ }
package/dist/inventory.js CHANGED
@@ -3,6 +3,12 @@ import { toolVersion } from "./version.js";
3
3
  export function createInventory(framework, frameworkVersion, fileCount, files, projectDiagnostics, configs) {
4
4
  const suites = files.flatMap((file) => file.suites);
5
5
  const tests = files.flatMap((file) => file.tests);
6
+ // Mocha shares one root suite across files; a root .only test drops every child suite.
7
+ if (framework === 'mocha' && tests.some((test) => test.suiteId === null && test.isOnly)) {
8
+ for (const test of tests)
9
+ if (test.suiteId !== null)
10
+ test.isOnly = false;
11
+ }
6
12
  const diagnostics = [...projectDiagnostics, ...files.flatMap((file) => file.diagnostics)];
7
13
  return {
8
14
  schemaVersion: 1,
package/dist/model.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { CallExpression, Expression, Node } from 'oxc-parser';
2
2
  import type { FunctionNode } from './ast.ts';
3
+ import type { Scope } from './extract.ts';
3
4
  import type { Annotation, DiagnosticCode, DiagnosticLevel, HookCounts, MetaValue } from './types.ts';
4
5
  import type { Value } from './values.ts';
5
6
  export type State = 'skip' | 'fixme' | 'todo' | 'expectedToFail';
@@ -39,6 +40,8 @@ export interface Problem {
39
40
  afterLoad?: boolean;
40
41
  /** The runner still runs the tests the file declared before the call that stops it loading, as WebdriverIO's Mocha. */
41
42
  keepsEarlierTests?: boolean;
43
+ /** The describe whose callback encountered the refusal, when its failure is contained by the runner. */
44
+ scope?: Scope;
42
45
  }
43
46
  export interface Title {
44
47
  text: string;
@@ -3,7 +3,7 @@
3
3
  * that gives none. A command runs node:test when `--test` comes before any file, as `node build.js --test` passes it on
4
4
  * to the script.
5
5
  */
6
- export declare function nodeTestCommands(script: string): string[][];
6
+ export declare function nodeTestCommands(script: string, setups?: boolean): string[][];
7
7
  /**
8
8
  * A package.json script and those it runs in turn, each once: through `npm run`, `npm test`, `pnpm`, `yarn`,
9
9
  * `bun run`, or `npm-run-all`, `run-s` and `run-p`, whose names may be globs where `*` stops at a `:`.
@@ -58,7 +58,7 @@ const VALUE_OPTIONS = new Set([
58
58
  * that gives none. A command runs node:test when `--test` comes before any file, as `node build.js --test` passes it on
59
59
  * to the script.
60
60
  */
61
- export function nodeTestCommands(script) {
61
+ export function nodeTestCommands(script, setups = false) {
62
62
  const commands = [];
63
63
  for (const words of commandsOf(script)) {
64
64
  const node = words.findIndex((word) => /(^|[/\\])node(\.exe)?$/.test(word));
@@ -66,12 +66,21 @@ export function nodeTestCommands(script) {
66
66
  continue;
67
67
  let runsTests = false;
68
68
  const files = [];
69
+ const preload = [];
69
70
  for (let index = node + 1; index < words.length; index++) {
70
71
  const word = words[index];
72
+ const [option] = word.split('=');
73
+ const setup = ['--import', '--require', '-r', '--test-global-setup'].includes(option);
71
74
  if (word === '--test')
72
75
  runsTests = true;
73
- else if (VALUE_OPTIONS.has(word))
76
+ else if (setup && word.includes('='))
77
+ preload.push(word.slice(word.indexOf('=') + 1));
78
+ else if (VALUE_OPTIONS.has(word)) {
79
+ const value = words.at(index + 1);
80
+ if (setup && value !== undefined)
81
+ preload.push(value);
74
82
  index++;
83
+ }
75
84
  else if (!word.startsWith('-')) {
76
85
  if (!runsTests)
77
86
  break;
@@ -79,7 +88,7 @@ export function nodeTestCommands(script) {
79
88
  }
80
89
  }
81
90
  if (runsTests)
82
- commands.push(files);
91
+ commands.push(setups ? preload : files);
83
92
  }
84
93
  return commands;
85
94
  }
package/dist/records.d.ts CHANGED
@@ -64,6 +64,7 @@ export interface FileConfig {
64
64
  forTest(test: TestRecord, suites: SuiteRecord[]): {
65
65
  projects: string[] | null;
66
66
  defaults: ConfigDefaults | null;
67
+ forbidOnly?: FileConfig['forbidOnly'];
67
68
  };
68
69
  /** Vitest's tags; null when the scan can't work them out, or the projects that run the file define different ones. */
69
70
  tags: VitestTags | null;
package/dist/records.js CHANGED
@@ -204,6 +204,7 @@ class RecordBuilder {
204
204
  diagnostics = [];
205
205
  /** The line of the first problem for which the runner refuses the file; null when it loads. */
206
206
  rejectedAt = null;
207
+ rejectedScopes = new Map();
207
208
  /** Whether the tests declared before the line that stops the file loading still run. */
208
209
  keepsEarlierTests = false;
209
210
  /** Jest: the describes with a test of their own that uses `.only`, which then keep their mode from their others. */
@@ -218,7 +219,7 @@ class RecordBuilder {
218
219
  build(extraction) {
219
220
  const duplicates = this.duplicates(extraction.tests);
220
221
  const tags = this.options.framework === 'vitest' ? (this.options.config?.tags ?? null) : null;
221
- const testProblems = extraction.tests.flatMap((test) => test.problems);
222
+ const testProblems = extraction.tests.flatMap((test) => test.problems.map((item) => ({ ...item, scope: test.scope })));
222
223
  // With the config's tags known, what they do is in the records, unless a tag can't be worked out.
223
224
  const isTagMissing = [...extraction.problems, ...testProblems].some((item) => item.code === 'unresolved-tag');
224
225
  const undefinedUses = tags?.isStrict ? undefinedTags(extraction, tags) : [];
@@ -233,7 +234,14 @@ class RecordBuilder {
233
234
  (item.level ?? LEVELS[item.code]) === 'error');
234
235
  // Each of these problems points at the code that causes it. Vitest meets the tags in the order they are listed.
235
236
  const firstTag = undefinedUses.find((use) => use.isSure)?.problem;
236
- const lines = [...rejecting, ...(firstTag ? [firstTag] : [])].map((item) => this.parsed.source.line(item.node.start));
237
+ const contained = (item) => ['node', 'bun'].includes(this.options.framework) && item.scope?.kind === 'describe';
238
+ for (const item of rejecting.filter(contained).sort((a, b) => a.node.start - b.node.start)) {
239
+ const scope = item.scope;
240
+ const offset = item.node.start;
241
+ if (!this.rejectedScopes.has(scope))
242
+ this.rejectedScopes.set(scope, { offset, line: this.parsed.source.line(offset) });
243
+ }
244
+ const lines = [...rejecting.filter((item) => !contained(item)), ...(firstTag ? [firstTag] : [])].map((item) => this.parsed.source.line(item.node.start));
237
245
  if (lines.length > 0)
238
246
  this.rejectedAt = Math.min(...lines);
239
247
  this.keepsEarlierTests = rejecting.length > 0 && rejecting.every((item) => item.keepsEarlierTests === true);
@@ -244,6 +252,12 @@ class RecordBuilder {
244
252
  ...extraction.suites.filter((suite) => suite.declaration.isOnly).map((suite) => suite.scope.parent),
245
253
  ];
246
254
  this.focusedBelow = new Set(focusedAt.flatMap((scope) => outward(scope)));
255
+ // A named callback can place a child before its calling parent in source order.
256
+ for (const { scope, declaration } of extraction.suites) {
257
+ const parents = outward(scope).slice(1, -1).reverse();
258
+ // Mark describe ids so that a describe and test with the same title in the same place differ.
259
+ this.suiteIds.set(scope, this.id(['describe', this.describeTitles(parents), declaration.title?.withoutTags ?? '']));
260
+ }
247
261
  const suites = extraction.suites.map((suite) => this.suite(suite));
248
262
  const tests = extraction.tests.map((test) => this.test(test, suites));
249
263
  for (const item of problems) {
@@ -265,6 +279,17 @@ class RecordBuilder {
265
279
  };
266
280
  }
267
281
  diagnostic(item, testId = null) {
282
+ if (item.scope && this.rejectedScopes.has(item.scope)) {
283
+ const effect = this.options.framework === 'node'
284
+ ? 'fails this describe; its earlier tests and tests outside it still run'
285
+ : 'fails this describe; tests outside it still run';
286
+ item = {
287
+ ...item,
288
+ message: item.message
289
+ .replace('fails the file and runs none of its tests', effect)
290
+ .replace('fails the file', effect),
291
+ };
292
+ }
268
293
  return toDiagnostic(item, this.options.relativeFilePath, this.parsed.source, testId);
269
294
  }
270
295
  position(node) {
@@ -292,8 +317,8 @@ class RecordBuilder {
292
317
  * Reports a `.only` that the config's `forbidOnly` makes fail the run, at `located`; one under a condition is a
293
318
  * warning. `call` is the `.only` call when it is in this file, whose callee the diagnostic shows.
294
319
  */
295
- forbidOnly(located, call) {
296
- const forbid = this.options.config?.forbidOnly ?? null;
320
+ forbidOnly(located, call, override) {
321
+ const forbid = override === undefined ? (this.options.config?.forbidOnly ?? null) : override;
297
322
  if (forbid === null)
298
323
  return;
299
324
  const callee = call && snippet(this.parsed.source.text.slice(call.callee.start, call.callee.end));
@@ -302,16 +327,16 @@ class RecordBuilder {
302
327
  }
303
328
  suite(pending) {
304
329
  const { scope, declaration, call } = pending;
305
- if (declaration.isOnly)
330
+ const skipped = this.options.framework === 'vitest' &&
331
+ outward(scope).some((parent) => parent.states.some((setting) => ['skip', 'todo'].includes(setting.state) && setting.condition === null));
332
+ if (declaration.isOnly && !skipped)
306
333
  this.forbidOnly(pending.site ?? call, pending.site ? null : call);
307
334
  const parents = outward(scope).slice(1, -1).reverse();
308
335
  const title = declaration.title;
309
- // Suite ids are marked so that a describe and a test with the same title in the same place differ.
310
- const id = this.id(['describe', this.describeTitles(parents), title?.withoutTags ?? '']);
311
- this.suiteIds.set(scope, id);
336
+ const id = this.suiteIds.get(scope);
312
337
  const chosen = chooseState(scope.states.map((setting) => ({ setting, source: 'suite' })));
313
338
  const state = chosen?.setting.state;
314
- const fn = declaration.fn;
339
+ const fn = declaration.fn ?? declaration.hashed;
315
340
  return {
316
341
  id,
317
342
  parentId: parents.length > 0 ? this.suiteIds.get(parents[parents.length - 1]) : null,
@@ -402,6 +427,18 @@ class RecordBuilder {
402
427
  const nearest = scopes.findIndex((scope) => scope.isOnly);
403
428
  return nearest !== -1 && !this.focusedBelow.has(scopes[nearest]) ? nearest : null;
404
429
  }
430
+ /** Mocha keeps a suite's own focused tests first, otherwise only its innermost focused suites. */
431
+ mochaFocus(pending, scopes) {
432
+ for (const scope of [...scopes].reverse()) {
433
+ if (this.focused.has(scope))
434
+ return pending.scope === scope && pending.declaration.isOnly;
435
+ if (scope.isOnly && !this.focusedBelow.has(scope))
436
+ return true;
437
+ if (!this.focusedBelow.has(scope))
438
+ return false;
439
+ }
440
+ return pending.declaration.isOnly;
441
+ }
405
442
  test(pending, suites) {
406
443
  const { declaration } = pending;
407
444
  const dependencies = this.options.dependencies(pending);
@@ -431,6 +468,7 @@ class RecordBuilder {
431
468
  const tagged = (own, tag, around) => tagsFirst ? [...own, ...tag, ...around] : [...own, ...around, ...tag];
432
469
  const jest = this.options.framework === 'jest' ? this.jestState(pending, scopes) : null;
433
470
  const focus = this.options.focusesLikeJasmine ? this.jasmineFocus(pending, scopes) : undefined;
471
+ const mocha = !this.options.focusesLikeJasmine && ['mocha', 'cypress', 'webdriverio'].includes(this.options.framework);
434
472
  // A focus inside an `xdescribe` runs, as the describe's own skip doesn't reach it; `pending()` still does. An
435
473
  // `xdescribe` inside the focus stays skipped.
436
474
  const declaredSkip = (scope, index, setting) => typeof focus === 'number' &&
@@ -459,7 +497,12 @@ class RecordBuilder {
459
497
  ...around.filter((candidate) => !candidate.overrides),
460
498
  ]);
461
499
  // When the runner refuses the file, no test in it runs, whatever else is written, or none after the refused call.
462
- const rejected = this.rejectedAt !== null && !(this.keepsEarlierTests && this.parsed.source.line(located.start) < this.rejectedAt);
500
+ const scopeFailure = scopes
501
+ .map((scope) => this.rejectedScopes.get(scope))
502
+ .find((failure) => failure !== undefined && (this.options.framework === 'bun' || located.start >= failure.offset));
503
+ const rejected = scopeFailure !== undefined ||
504
+ (this.rejectedAt !== null &&
505
+ !(this.keepsEarlierTests && this.parsed.source.line(located.start) < this.rejectedAt));
463
506
  const state = rejected ? 'notLoaded' : (chosen?.setting.state ?? 'active');
464
507
  const setting = rejected ? null : (chosen?.setting ?? null);
465
508
  const suitePath = [
@@ -477,7 +520,9 @@ class RecordBuilder {
477
520
  ? jest.isOnly
478
521
  : focus !== undefined
479
522
  ? focus !== null
480
- : declaration.isOnly || scopes.some((scope) => scope.isOnly) || fromTags?.only === true;
523
+ : mocha
524
+ ? this.mochaFocus(pending, scopes)
525
+ : declaration.isOnly || scopes.some((scope) => scope.isOnly) || fromTags?.only === true;
481
526
  const comments = this.options.comments === 'all' || (this.options.comments === 'non-active' && state !== 'active')
482
527
  ? pending.comments
483
528
  : [];
@@ -489,7 +534,7 @@ class RecordBuilder {
489
534
  const message = 'The test uses the bench fixture, which Vitest only provides in benchmark files such as *.bench.ts; elsewhere the test fails.';
490
535
  this.diagnostics.push(this.diagnostic(problem('bench-outside-benchmark-file', located, message), id));
491
536
  }
492
- if (declaration.isOnly)
537
+ if (declaration.isOnly && this.options.framework !== 'vitest')
493
538
  this.forbidOnly(located, pending.site ? null : pending.call);
494
539
  // A loop the scan counts is described by caseCount, as a table is.
495
540
  if (pending.loops.includes(null)) {
@@ -531,8 +576,8 @@ class RecordBuilder {
531
576
  condition: setting?.condition ?? null,
532
577
  reason: setting?.reason ?? null,
533
578
  hasDynamicReason: setting?.hasDynamicReason ?? false,
534
- stateSource: rejected ? 'file' : (chosen?.source ?? null),
535
- stateLine: rejected ? this.rejectedAt : (setting?.line ?? null),
579
+ stateSource: scopeFailure ? 'suite' : rejected ? 'file' : (chosen?.source ?? null),
580
+ stateLine: scopeFailure ? scopeFailure.line : rejected ? this.rejectedAt : (setting?.line ?? null),
536
581
  isParallel: mode === 'parallel',
537
582
  isSerial: mode === 'serial',
538
583
  tags,
@@ -568,7 +613,14 @@ class RecordBuilder {
568
613
  isInFunction: pending.isInFunction,
569
614
  projects: null,
570
615
  };
571
- const { projects, defaults } = this.options.config?.forTest(record, suites) ?? { projects: null, defaults: null };
616
+ const { projects, defaults, forbidOnly } = this.options.config?.forTest(record, suites) ?? {
617
+ projects: null,
618
+ defaults: null,
619
+ };
620
+ const skippedOnly = chosen && ['skip', 'todo'].includes(chosen.setting.state) && chosen.setting.condition === null;
621
+ if (declaration.isOnly && this.options.framework === 'vitest' && !skippedOnly) {
622
+ this.forbidOnly(located, pending.site ? null : pending.call, forbidOnly);
623
+ }
572
624
  return {
573
625
  ...withConfig(record, defaults),
574
626
  isParallel: record.isParallel || (mode === null && defaults?.parallel === true),
package/dist/resolve.js CHANGED
@@ -433,6 +433,8 @@ export function moduleResolver(root) {
433
433
  const reader = (fromFile, map = null) => (specifier) => {
434
434
  const directory = path.dirname(fromFile);
435
435
  const aliased = map?.aliases.map((alias) => mapped(specifier, alias)).find((names) => names !== null);
436
+ if (aliased?.length === 0)
437
+ return { reason: 'has a config alias whose replacement could not be worked out' };
436
438
  // Vite takes `/src/x` from its root first, unless it is already a path inside the root.
437
439
  const fromRoot = (name) => map?.root && name.startsWith('/') && !name.startsWith(map.root + path.sep)
438
440
  ? [path.join(map.root, name), name]
package/dist/scan.js CHANGED
@@ -197,7 +197,7 @@ export async function scan(options) {
197
197
  // Searched from the folder itself, as a folder named like `(auth)` would be read as a glob in a pattern.
198
198
  const setupFiles = await Promise.all([...setupDirs].map((folder) => glob(SCRIPT_FILES, { cwd: folder, absolute: true, ignore: ['**/node_modules/**'] })));
199
199
  const candidates = setupFiles.flat().map((file) => path.resolve(file));
200
- const configDependencies = new ConfigDependencies(framework, runs, readerFor, candidates);
200
+ const configDependencies = new ConfigDependencies(framework, runs, readerFor, candidates, root);
201
201
  // Many tests of a file compare against one folder, so each is listed once.
202
202
  const listed = new Map();
203
203
  const list = (folder) => {
package/dist/types.d.ts CHANGED
@@ -312,9 +312,9 @@ export interface TestRecord {
312
312
  isFixme: boolean;
313
313
  isTodo: boolean;
314
314
  isExpectedToFail: boolean;
315
- /** The runner refuses to load the file; a diagnostic at `stateLine` says why. */
315
+ /** The runner did not load this test, possibly because its describe failed; a diagnostic at `stateLine` says why. */
316
316
  isNotLoaded: boolean;
317
- /** The test or a describe around it uses `.only`. */
317
+ /** The test is selected by a `.only`, following the runner's focus rules. */
318
318
  isOnly: boolean;
319
319
  /** The state applies only when a condition holds, as with `test.skip(condition)` or `skipIf`. */
320
320
  isConditional: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "test-inventory",
3
- "version": "0.9.1",
3
+ "version": "0.10.1",
4
4
  "description": "Lists every Playwright, Vitest, Jest, Mocha, Jasmine, Cypress, WebdriverIO, node:test and Bun test from the source code, without running it: its state and why, tags, an id that survives a move, a hash of everything it runs, and the tests a change can affect.",
5
5
  "keywords": [
6
6
  "testing",
@@ -41,6 +41,7 @@
41
41
  "default": "./dist/index.js"
42
42
  },
43
43
  "./schema/v1.json": "./schema/v1.json",
44
+ "./schema/diff-v1.json": "./schema/diff-v1.json",
44
45
  "./package.json": "./package.json"
45
46
  },
46
47
  "main": "./dist/index.js",