Repository navigation
Expand file tree
/
Copy pathselect-affected-tests.test.ts
More file actions
654 lines (589 loc) · 32.2 KB
/
Copy pathselect-affected-tests.test.ts
File metadata and controls
654 lines (589 loc) · 32.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
import { afterAll, describe, expect, it } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync, spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import {
changedFiles,
changedOutsideTree,
closureSummaries,
dedupeFilters,
listWorkspacePackages,
moduleSpecifiers,
PATH_WALKER,
PATH_WALKER_FILE,
outsideTreeReasons,
packageClosures,
parseWorkspaceGlobs,
readHeavyProject,
selectAffectedTests,
trackedFiles,
} from '../select-affected-tests.mjs';
import { shardTotal } from '../../../scripts/ci-shard-matrix.mjs';
import { parse as parseYaml } from 'yaml';
import { jobBlock, rootCi, triggerBlock, UI_JOBS, uiRun, withoutComments } from './helpers/root-ci';
/**
* objectui#12214 — the affected-test selector behind the two-speed `Test` lane.
*
* The fixture tree below is the smallest workspace that exercises every rule
* the selector's header states, each in BOTH directions: a change that must
* reach a test, and a change that must not. The live-tree cases at the end hold
* the selector to the real repository: the package graph agrees with turbo's,
* the `dom-heavy` project still parses, and the CLI reaches a verdict.
*/
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const tmpRoots: string[] = [];
afterAll(() => {
for (const dir of tmpRoots) fs.rmSync(dir, { recursive: true, force: true });
});
function fixture(files: Record<string, string>): { root: string; tracked: string[] } {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'select-affected-12214-'));
tmpRoots.push(root);
for (const [rel, text] of Object.entries(files)) {
fs.mkdirSync(path.join(root, path.dirname(rel)), { recursive: true });
fs.writeFileSync(path.join(root, rel), text);
}
return { root, tracked: Object.keys(files).sort() };
}
/** A test source that reads `args` (joined onto its own directory) with `fs`. */
const reader = (read: string, extraImports = '') =>
"import { readFileSync } from 'node:fs';\n" +
"import { dirname, join } from 'node:path';\n" +
"import { fileURLToPath } from 'node:url';\n" +
extraImports +
'const HERE = dirname(fileURLToPath(import.meta.url));\n' +
`${read};\n`;
const manifest = (name: string, deps: Record<string, string> = {}) =>
JSON.stringify({ name, version: '0.0.0', dependencies: deps });
/** A root config carrying the two shapes `readHeavyProject` reads. */
const ROOT_CONFIG = `import path from 'path';
import { guard } from './scripts/guard.mjs';
guard();
const heavyDomTests = [
// a comment line the reader must skip
'packages/heavy-user/src/heavy.test.tsx',
];
export default {
test: {
projects: [
{
extends: true,
test: {
name: 'dom-heavy',
environment: 'happy-dom',
setupFiles: [path.resolve(__dirname, 'vitest.setup.dom.tsx')],
include: [...heavyDomTests],
},
},
],
},
};
`;
function workspace() {
return fixture({
'pnpm-workspace.yaml': "packages:\n - 'packages/*'\n",
'package.json': manifest('root'),
'vitest.config.mts': ROOT_CONFIG,
'vitest.setup.dom-light.tsx': "import '@fx/locales';\n",
'vitest.setup.dom.tsx': "import './vitest.setup.dom-light';\nimport '@fx/registry';\n",
'scripts/guard.mjs': 'export function guard() {}\n',
'scripts/helper.mjs': 'export const x = 1;\n',
'scripts/__tests__/gate.test.ts': "import '../helper.mjs';\n",
'README.md': '# fixture\n',
'content/page.md': 'docs\n',
'packages/locales/package.json': manifest('@fx/locales'),
'packages/locales/src/index.ts': 'export const en = {};\n',
'packages/registry/package.json': manifest('@fx/registry'),
'packages/registry/src/index.ts': 'export const r = 1;\n',
'packages/a/package.json': manifest('@fx/a'),
'packages/a/tsconfig.json': '{}\n',
'packages/a/src/index.ts': 'export const a = 1;\n',
'packages/a/src/a.test.ts': "import { a } from './index';\n",
'packages/b/package.json': manifest('@fx/b', { '@fx/a': 'workspace:*' }),
'packages/b/src/index.ts': "import { a } from '@fx/a';\nexport const b = a;\n",
'packages/b/src/b.test.ts': "import { b } from './index';\n",
'packages/c/package.json': manifest('@fx/c'),
'packages/c/src/index.ts': 'export const c = 1;\n',
'packages/c/src/plain.test.ts': "import { c } from './index';\n",
'packages/c/src/plain.test.tsx': "import { c } from './index';\n",
'packages/c/src/reads.test.ts': "import './helpers/tree';\n",
'packages/c/src/helpers/tree.ts': "import fs from 'node:fs';\nexport const t = fs.existsSync('.');\n",
'packages/c/src/undeclared.test.ts': "import { a } from '@fx/a';\n",
'packages/c/src/reach.test.ts': "import { b } from '../../b/src/index';\n",
'packages/c/src/own-read.test.ts': reader("readFileSync(join(HERE, '..', 'fixtures', 'x.json'), 'utf8')"),
'packages/c/src/other-read.test.ts': reader("readFileSync(join(HERE, '..', '..', 'a', 'src', 'index.ts'), 'utf8')"),
'packages/c/src/cwd-read.test.ts': reader("readFileSync(join(process.cwd(), 'x.json'), 'utf8')"),
'packages/c/src/var-read.test.ts': reader('const files = [HERE];\nfor (const f of files) readFileSync(f)'),
'packages/c/src/aliased-read.test.ts': "import { readFileSync as rf } from 'node:fs';\nrf(new URL('./x.json', import.meta.url));\n",
'packages/c/src/ts-read.test.ts': reader("readFileSync(join(HERE, 'x.json'), 'utf8')", "import ts from 'typescript';\n"),
'packages/c/src/passed-read.test.ts': reader("readFileSync(join(HERE, 'x.json'), 'utf8');\n[HERE].map(readFileSync)"),
'packages/c/src/rebound-read.test.ts': reader(
"readFileSync(join(HERE, 'x.json'), 'utf8');\nconst r = readFileSync;\nr('/etc/hosts')",
),
'packages/c/src/escapes.test.ts': "import '../../../scripts/helper.mjs';\n",
'packages/heavy-user/package.json': manifest('@fx/heavy-user'),
'packages/heavy-user/src/heavy.test.tsx': 'export {};\n',
});
}
type Affected = Extract<ReturnType<typeof selectAffectedTests>, { mode: 'affected' }>;
function affected(root: string, tracked: string[], changed: string[]): Affected {
const verdict = selectAffectedTests({ root, tracked, changed });
expect(verdict.mode, `expected an affected verdict for ${changed.join(', ')}`).toBe('affected');
return verdict as Affected;
}
function full(root: string, tracked: string[], changed: string[]): string[] {
const verdict = selectAffectedTests({ root, tracked, changed });
expect(verdict.mode, `expected a full run for ${changed.join(', ')}`).toBe('full');
return (verdict as { reasons: string[] }).reasons;
}
describe('select-affected-tests — the package graph (objectui#12214)', () => {
it('selects the changed package and its dependents, and not an unrelated package', () => {
const { root, tracked } = workspace();
const v = affected(root, tracked, ['packages/a/src/index.ts']);
expect(v.changedPackages).toEqual(['@fx/a']);
expect(v.affectedPackages).toEqual(['@fx/a', '@fx/b']);
expect(v.filters).toContain('packages/a/');
expect(v.filters).toContain('packages/b/');
expect(v.filters).not.toContain('packages/c/');
expect(v.filters.some((f) => f.includes('plain.test'))).toBe(false);
});
it('a dependency does not pull in its own dependencies', () => {
const { root, tracked } = workspace();
const v = affected(root, tracked, ['packages/b/src/index.ts']);
expect(v.affectedPackages).toEqual(['@fx/b']);
expect(v.filters).not.toContain('packages/a/');
});
});
describe('select-affected-tests — the always-on set', () => {
const { root, tracked } = workspace();
const v = affected(root, tracked, ['content/page.md']);
const why = new Map(v.alwaysOn.map((a) => [a.file, a.why]));
it('a docs-only change selects the always-on set and no package', () => {
expect(v.affectedPackages).toEqual([]);
expect(v.filters.length).toBeGreaterThan(0);
});
it('keeps a test outside every package', () => {
expect(why.get('scripts/__tests__/gate.test.ts')).toBe('outside every workspace package');
});
it('keeps a test whose RELATIVE closure reads the disk, not only one that imports fs itself', () => {
expect(why.get('packages/c/src/reads.test.ts')).toBe('reads the disk or spawns a process');
});
it('keeps a test that reaches a file outside every package', () => {
expect(why.get('packages/c/src/escapes.test.ts')).toMatch(/reaches the repository root outside packages\/c/);
});
it('does not keep a test whose only edges past its package are into other packages (objectstack#31520)', () => {
expect(why.has('packages/c/src/undeclared.test.ts')).toBe(false);
expect(why.has('packages/c/src/reach.test.ts')).toBe(false);
expect(v.attributed).toEqual([]);
expect(v.filters.some((f) => f.includes('undeclared.test') || f.includes('reach.test'))).toBe(false);
});
it('leaves out a test the package graph can place', () => {
expect(why.has('packages/c/src/plain.test.ts')).toBe(false);
expect(v.filters.some((f) => f.includes('plain.test'))).toBe(false);
});
});
describe('select-affected-tests — attributed test files (objectstack#31520)', () => {
// `undeclared.test.ts` (in @fx/c) imports @fx/a by name, which @fx/c does
// not declare; `reach.test.ts` (in @fx/c) imports a file of @fx/b, which
// depends on @fx/a. Neither is always-on; each is selected exactly when a
// package it reads is affected.
const { root, tracked } = workspace();
const attributedOf = (changed: string[]) => new Map(affected(root, tracked, changed).attributed.map((a) => [a.file, a.via]));
it('selects a test when the package it imports by name without declaring it changes', () => {
const v = affected(root, tracked, ['packages/a/src/index.ts']);
expect(v.filters).toContain('packages/c/src/undeclared.test.ts');
expect(attributedOf(['packages/a/src/index.ts']).get('packages/c/src/undeclared.test.ts')).toEqual(['@fx/a']);
});
it('selects a test when the package it reaches by a relative import changes', () => {
const v = affected(root, tracked, ['packages/b/src/index.ts']);
expect(v.filters).toContain('packages/c/src/reach.test.ts');
expect(attributedOf(['packages/b/src/index.ts']).get('packages/c/src/reach.test.ts')).toEqual(['@fx/b']);
});
it('selects a test when a dependency of the package it reaches changes, through that package', () => {
expect(affected(root, tracked, ['packages/a/src/index.ts']).filters).toContain('packages/c/src/reach.test.ts');
expect(attributedOf(['packages/a/src/index.ts']).get('packages/c/src/reach.test.ts')).toEqual(['@fx/a', '@fx/b']);
});
it('does not select either when only a package neither reads changes', () => {
const v = affected(root, tracked, ['packages/registry/src/index.ts']);
expect(v.attributed).toEqual([]);
expect(v.filters.some((f) => f.includes('undeclared.test') || f.includes('reach.test'))).toBe(false);
});
it('a change to its own package selects it through the package directory, not as an attributed file', () => {
const v = affected(root, tracked, ['packages/c/src/index.ts']);
expect(v.filters).toContain('packages/c/');
expect(v.attributed).toEqual([]);
});
});
describe('select-affected-tests — bounded disk readers (objectstack#31520)', () => {
// Each `packages/c` reader below reads through `fs`. Only a read the walker
// names inside a workspace package frees the test; everything else keeps it
// always-on, which is the answer every disk reader had before.
const { root, tracked } = workspace();
const docsOnly = affected(root, tracked, ['content/page.md']);
const why = new Map(docsOnly.alwaysOn.map((a) => [a.file, a.why]));
it('the walker is loaded here, nested as ui/ of objectstack', () => {
expect(typeof PATH_WALKER).toBe('function');
});
it('frees a test whose reads stay in its own package, and selects it with that package', () => {
expect(why.has('packages/c/src/own-read.test.ts')).toBe(false);
expect(docsOnly.filters.some((f) => f.includes('own-read.test'))).toBe(false);
expect(affected(root, tracked, ['packages/c/src/index.ts']).filters).toContain('packages/c/');
expect(affected(root, tracked, ['packages/a/src/index.ts']).filters.some((f) => f.includes('own-read.test'))).toBe(false);
});
it('frees a test that reads another package by a named path, and selects it when that package changes', () => {
expect(why.has('packages/c/src/other-read.test.ts')).toBe(false);
const v = affected(root, tracked, ['packages/a/src/index.ts']);
expect(v.filters).toContain('packages/c/src/other-read.test.ts');
expect(new Map(v.attributed.map((a) => [a.file, a.via])).get('packages/c/src/other-read.test.ts')).toEqual(['@fx/a']);
expect(affected(root, tracked, ['packages/registry/src/index.ts']).filters.some((f) => f.includes('other-read.test'))).toBe(
false,
);
});
it('keeps a test whose read goes through process.cwd(), an unnamed argument, an aliased import or a disk-reading library', () => {
for (const file of ['cwd-read', 'var-read', 'aliased-read', 'ts-read']) {
expect(why.get(`packages/c/src/${file}.test.ts`), file).toBe('reads the disk or spawns a process');
}
});
it('keeps a test that passes or re-binds a named fs read, even beside a bounded read', () => {
for (const file of ['passed-read', 'rebound-read']) {
expect(why.get(`packages/c/src/${file}.test.ts`), file).toBe('reads the disk or spawns a process');
}
});
it('keeps every disk reader always-on when the walker is absent (a standalone tree)', () => {
const v = selectAffectedTests({ root, tracked, changed: ['content/page.md'], walker: null });
expect(v.mode).toBe('affected');
const standalone = new Map((v as Affected).alwaysOn.map((a) => [a.file, a.why]));
expect(standalone.get('packages/c/src/own-read.test.ts')).toBe('reads the disk or spawns a process');
expect(standalone.get('packages/c/src/other-read.test.ts')).toBe('reads the disk or spawns a process');
});
});
describe('select-affected-tests — what forces a full run', () => {
const { root, tracked } = workspace();
it.each([
['package.json', /package\.json change is a full-run trigger/],
['packages/c/package.json', /package\.json change is a full-run trigger/],
['packages/a/tsconfig.json', /tsconfig\.json change is a full-run trigger/],
['vitest.config.mts', /vitest\.config\.mts change is a full-run trigger/],
['pnpm-lock.yaml', /repository-root file that is not documentation/],
['patches/x.patch', /dependency patch/],
['scripts/guard.mjs', /root vitest config or a setup file imports it/],
['vitest.setup.dom-light.tsx', /root vitest config or a setup file imports it/],
['packages/locales/src/index.ts', /@fx\/locales is affected and a broad root vitest setup file imports it/],
])('%s', (changed, reason) => {
expect(full(root, tracked, [changed]).join('\n')).toMatch(reason);
});
it('a root documentation file is not a full-run trigger', () => {
affected(root, tracked, ['README.md']);
});
it('a script no config imports is not a full-run trigger', () => {
affected(root, tracked, ['scripts/helper.mjs']);
});
});
describe('select-affected-tests — the heavy DOM setup', () => {
it('a package only the heavy setup imports adds the dom-heavy test files instead of running everything', () => {
const { root, tracked } = workspace();
const v = affected(root, tracked, ['packages/registry/src/index.ts']);
expect(v.heavyEdge).toEqual(['@fx/registry']);
expect(v.filters).toContain('packages/heavy-user/src/heavy.test.tsx');
});
it('no heavy edge, no heavy tests', () => {
const { root, tracked } = workspace();
const v = affected(root, tracked, ['packages/c/src/index.ts']);
expect(v.heavyEdge).toEqual([]);
expect(v.filters).not.toContain('packages/heavy-user/src/heavy.test.tsx');
});
it('refuses a config whose dom-heavy project it cannot read, rather than guessing', () => {
expect(() => readHeavyProject('export default {}')).toThrow(/dom-heavy/);
expect(() =>
readHeavyProject(ROOT_CONFIG.replace(/'packages\/heavy-user\/src\/heavy\.test\.tsx',/, '')),
).toThrow(/empty/);
});
});
/**
* objectstack#25868 — the tree nested as `ui/` of a monorepo, the layout the
* root `ci.yml` runs it in. The tree's own files are the fixture above; the
* parent holds the one workspace file, the lockfile and its own packages:
* `@os/base` <- `@os/mid` (runtime) <- the tree's `@fx/a` (dev), `@os/mid`
* dev-depends on `@os/tooling`, and `@os/other` is unrelated.
*/
function nestedWorkspace() {
const tree = workspace();
const files: Record<string, string> = {
'pnpm-workspace.yaml': "packages:\n - 'packages/*'\n - ui\n - 'ui/packages/*'\n",
'package.json': manifest('monorepo'),
'pnpm-lock.yaml': 'lockfileVersion: 9.0\n',
'README.md': '# monorepo\n',
'packages/base/package.json': manifest('@os/base'),
'packages/base/src/index.ts': 'export const base = 1;\n',
'packages/mid/package.json': JSON.stringify({
name: '@os/mid',
version: '0.0.0',
dependencies: { '@os/base': 'workspace:*' },
devDependencies: { '@os/tooling': 'workspace:*' },
}),
'packages/tooling/package.json': manifest('@os/tooling'),
'packages/tooling/src/index.ts': 'export const t = 1;\n',
'packages/other/package.json': manifest('@os/other'),
'packages/other/src/index.ts': 'export const o = 1;\n',
};
for (const rel of tree.tracked) {
if (rel === 'pnpm-workspace.yaml') continue; // a nested workspace root is ignored; the parent's governs
const text = fs.readFileSync(path.join(tree.root, rel), 'utf8');
files[`ui/${rel}`] =
rel === 'packages/a/package.json'
? JSON.stringify({ name: '@fx/a', version: '0.0.0', devDependencies: { '@os/mid': 'workspace:*' } })
: text;
}
const { root } = fixture(files);
const ui = path.join(root, 'ui');
return { monorepo: root, root: ui, tracked: tree.tracked.filter((f) => f !== 'pnpm-workspace.yaml') };
}
describe('select-affected-tests — nested as ui/ of a monorepo (objectstack#25868)', () => {
it('a change outside the tree that every test installs or builds from is a full run', () => {
const { root } = nestedWorkspace();
const reasons = (outside: string[]) => outsideTreeReasons({ root, outside });
expect(reasons(['pnpm-lock.yaml'])[0]).toMatch(/^pnpm-lock\.yaml: a workspace-root file that is not documentation/);
expect(reasons(['package.json'])).toHaveLength(1);
expect(reasons(['patches/x@1.0.0.patch'])[0]).toMatch(/a dependency patch/);
// A package the tree depends on, and what that package depends on at run time.
expect(reasons(['packages/mid/src/index.ts'])[0]).toMatch(/@os\/mid changed, .* \(through @fx\/a\)$/);
expect(reasons(['packages/base/src/index.ts'])[0]).toMatch(/@os\/base changed/);
});
it('a change outside the tree that no test runs through is not', () => {
const { root } = nestedWorkspace();
// An outer package's devDependency is its own test tooling, not its built output.
for (const rel of [
'packages/tooling/src/index.ts',
'packages/other/src/index.ts',
'README.md',
'docs/guide.md',
'.github/workflows/ci.yml',
'scripts/gate.mjs',
]) {
expect(outsideTreeReasons({ root, outside: [rel] }), rel).toEqual([]);
}
});
it('reads the tree as before when nothing outside it changed, and turns full when the lockfile did', () => {
const { root, tracked } = nestedWorkspace();
expect(listWorkspacePackages(root).map((p) => p.dir)).toContain('packages/a');
const v = affected(root, tracked, ['packages/c/src/index.ts']);
expect(v.affectedPackages).toEqual(['@fx/c']);
const outside = ['docs/guide.md', 'packages/other/src/index.ts'];
expect(selectAffectedTests({ root, tracked, changed: ['packages/c/src/index.ts'], outside }).mode).toBe('affected');
const verdict = selectAffectedTests({ root, tracked, changed: ['packages/c/src/index.ts'], outside: ['pnpm-lock.yaml'] });
expect(verdict.mode).toBe('full');
});
it('git hands the tree its own changes and the monorepo its own, both through --relative', () => {
const { monorepo, root } = nestedWorkspace();
const git = (...args: string[]) =>
execFileSync('git', ['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.invalid', ...args], {
cwd: monorepo,
encoding: 'utf8',
});
git('init', '-q');
git('add', '-A');
git('commit', '-q', '-m', 'base');
fs.appendFileSync(path.join(root, 'packages/c/src/index.ts'), 'export const d = 2;\n');
fs.appendFileSync(path.join(monorepo, 'pnpm-lock.yaml'), '# moved\n');
git('commit', '-q', '-am', 'change');
expect(changedFiles(root, 'HEAD~1')).toEqual(['packages/c/src/index.ts']);
expect(changedOutsideTree(root, 'HEAD~1')).toEqual(['pnpm-lock.yaml']);
});
});
describe('select-affected-tests — readers', () => {
it('drops a filter another one already matches, as the vitest invocation guard requires (objectui#7814)', () => {
expect(dedupeFilters(['packages/c/src/plain.test.tsx', 'packages/c/src/plain.test.ts', 'packages/c/'])).toEqual([
'packages/c/',
]);
expect(dedupeFilters(['x/a.test.tsx', 'x/a.test.ts'])).toEqual(['x/a.test.ts']);
});
it('reads every import spelling the selector depends on', () => {
const { specifiers, globsTheTree } = moduleSpecifiers(
[
"import a from './a';",
"import type { B } from './b';",
"export * from './c';",
"import './d';",
"const e = await import('./e');",
"const f = require('./f');",
"vi.mock('./g', async (importOriginal) => ({ ...(await importOriginal()) }));",
'import {\n h,\n i,\n} from "./h";',
"const files = import.meta.glob('../**/*.md');",
].join('\n'),
);
expect(specifiers.sort()).toEqual(['./a', './b', './c', './d', './e', './f', './g', './h']);
expect(globsTheTree).toBe(true);
});
it('refuses a workspace glob shape it does not know', () => {
expect(parseWorkspaceGlobs("packages:\n - 'packages/*'\n - docs\n")).toEqual(['packages/*', 'docs']);
expect(() => parseWorkspaceGlobs("packages:\n - 'packages/**'\n")).toThrow(/does not know/);
expect(() => parseWorkspaceGlobs('catalog: {}\n')).toThrow(/declares no packages/);
});
it('summarises an import CYCLE without looping, every member seeing the whole cycle', () => {
const { root } = fixture({
'p/x.ts': "import './y';\n",
'p/y.ts': "import './x';\nimport 'node:fs';\n",
});
const summaries = closureSummaries(root, ['p/x.ts'], new Set(), () => 'p');
expect(summaries.get('p/x.ts')?.readsDisk).toBe(true);
expect(summaries.get('p/y.ts')?.readsDisk).toBe(true);
});
});
describe('select-affected-tests — the live tree', () => {
const packages = listWorkspacePackages(repoRoot);
const { dependentClosure } = packageClosures(packages);
it('agrees with turbo on who depends on whom', () => {
// The header promises `turbo ls --affected`'s answer. Held, not assumed, on
// a leaf, a mid-graph and a root package.
const turbo = path.join(repoRoot, 'node_modules/.bin/turbo');
for (const name of ['@object-ui/plugin-kanban', '@object-ui/app-shell', '@object-ui/i18n']) {
const out = execFileSync(turbo, ['ls', name, '--output=json'], { cwd: repoRoot, encoding: 'utf8' });
const reading = JSON.parse(out) as { packages: Array<{ name: string; dependents: string[] }> };
const theirs = reading.packages.find((p) => p.name === name)?.dependents ?? [];
expect(theirs.length, `turbo named no dependents for ${name}; a broken reading, not a leaf`).toBeGreaterThan(
name === '@object-ui/app-shell' ? 0 : 1,
);
expect([...(dependentClosure.get(name) ?? [])].sort()).toEqual([...theirs].sort());
}
});
it('reads the real dom-heavy project, and every file it names is tracked', () => {
const heavy = readHeavyProject(fs.readFileSync(path.join(repoRoot, 'vitest.config.mts'), 'utf8'));
expect(heavy.setupFile).toMatch(/^vitest\.setup\.[^/]+$/);
const tracked = new Set(trackedFiles(repoRoot));
expect(tracked.has(heavy.setupFile)).toBe(true);
expect(heavy.tests.filter((t) => !tracked.has(t))).toEqual([]);
});
it('a change to the imported path walker selects what a change to the selector itself does (objectstack#31520)', () => {
// The walker lives outside ui/, so a change there arrives as `outside`. It
// must keep reaching this file's own tests, or an edit to it could narrow
// the selection with nothing here running to notice.
const self = 'scripts/__tests__/select-affected-tests.test.ts';
const walker = selectAffectedTests({ changed: [], outside: [PATH_WALKER_FILE] });
const selector = selectAffectedTests({ changed: ['scripts/select-affected-tests.mjs'] });
expect(walker.mode).toBe(selector.mode);
if (walker.mode === 'affected' && selector.mode === 'affected') {
expect(walker.filters).toEqual(selector.filters);
expect(walker.filters).toContain(self);
}
});
it('reaches a verdict from the command line, and an empty change still selects the always-on set', () => {
const out = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'select-affected-cli-')), 'filters.txt');
tmpRoots.push(path.dirname(out));
const run = spawnSync(process.execPath, ['scripts/select-affected-tests.mjs', '--base', 'HEAD', '--out', out], {
cwd: repoRoot,
encoding: 'utf8',
});
expect(run.status, run.stderr).toBe(0);
expect(run.stdout.trim().split('\n').pop()).toBe('mode=affected');
const filters = fs.readFileSync(out, 'utf8').trim().split('\n');
expect(filters.length).toBeGreaterThan(0);
expect(filters.every((f) => fs.existsSync(path.join(repoRoot, f)))).toBe(true);
});
it('answers "could not decide" with a non-zero exit, never a verdict', () => {
const run = spawnSync(process.execPath, ['scripts/select-affected-tests.mjs', '--base', 'no-such-ref-12214', '--explain'], {
cwd: repoRoot,
encoding: 'utf8',
});
expect(run.status).toBe(2);
expect(run.stdout).not.toMatch(/^mode=/m);
});
});
// objectui ci.yml's `test` job wired this selector; objectstack#25712 retired
// these pins with that file, and objectstack#25868 wired the selector into the
// root `test-ui` job that replaced it, so they read that job now.
describe("the root ci.yml's Test UI job wires the selector fail-open (objectui#12214, objectstack#25868)", () => {
const code = withoutComments(rootCi());
const job = jobBlock(code, UI_JOBS.test);
it('runs the full battery hourly on main, beside push', () => {
expect(triggerBlock(code)).toMatch(/^ {2}schedule:\n {4}- cron: '[^']+'$/m);
});
it('selects only on pull_request and merge_group, and treats every other event as full', () => {
const step = job.slice(job.indexOf('- name: Select the tests this change affects'));
expect(step).toMatch(/pull_request\)\n\s+if \[ -n "\$PR_BASE_REF" \]; then\n\s+base=\$\(git merge-base "refs\/remotes\/origin\/\$PR_BASE_REF" HEAD\) \|\| base=''/);
expect(step).toMatch(/merge_group\) base="\$QUEUE_BASE"/);
expect(step).toMatch(/\*\)\n\s+echo 'mode=full' >> "\$GITHUB_OUTPUT"/);
});
it('turns a selector that cannot decide into a full run, not a skip', () => {
const step = job.slice(job.indexOf('- name: Select the tests this change affects'));
expect(step).toContain('|| status=$?');
expect(step).toMatch(/verdict='mode=full'/);
// objectui#6221: the status must not be swallowed by a command substitution.
expect(step).not.toMatch(/\$\(node ui\/scripts\/select-affected-tests\.mjs/);
});
// objectstack#22034: the checkout is depth 1 and a step of its own fetches
// HEAD's whole ancestry and the base branch, not `fetch-depth: 0`'s every
// head and tag. Without it the select step below finds no origin/<base> and
// no merge base, and quietly runs the full suite.
it('fetches the history the diff base needs before it selects', () => {
const checkout = job.indexOf('uses: actions/checkout@');
const fetch = job.indexOf("- name: Fetch this commit's history and the base branch");
const select = job.indexOf('- name: Select the tests this change affects');
expect(checkout).toBeGreaterThan(-1);
expect(fetch).toBeGreaterThan(checkout);
expect(select).toBeGreaterThan(fetch);
const step = job.slice(fetch, select);
expect(step).toContain('deepen=(--unshallow)');
expect(step).toContain('git fetch --no-tags "${deepen[@]}" origin "$head" "${refspecs[@]}"');
expect(step).toContain("refspecs=('+refs/heads/main:refs/remotes/origin/main')");
expect(step).toContain('refspecs+=("+refs/heads/$PR_BASE_REF:refs/remotes/origin/$PR_BASE_REF")');
});
it('keeps the matrix width and the full-suite command for the full battery', () => {
// The width is the job's own `shard:` list, read by the monorepo's one reader of
// shard sizes (it refuses any other spelling); every `/N` the job's run step
// spells must be that width.
const shards = shardTotal(rootCi(), UI_JOBS.test);
const header = `- name: Run the ui tests (shard \${{ matrix.shard }}/${shards})`;
expect(job).toContain(header);
const run = job.slice(job.indexOf(header));
expect(run).toContain(`${uiRun('test')} --shard=\${{ matrix.shard }}/${shards}`);
expect(run).toContain(`pnpm --dir ui exec vitest run --shard=\${{ matrix.shard }}/${shards} --reporter=default --reporter=github-actions "\${filters[@]}"`);
});
});
// objectstack#22034: the four root ci.yml jobs that read git history check out
// at depth 1 and fetch only HEAD's ancestry and the base branch, in one step
// that is the same in all four. `fetch-depth: 0` fetched every head and every
// tag; a checkout that grows it back passes every other gate and silently
// undoes the measurement the fetch step's budget was sized from.
describe("the root ci.yml's history readers check out at depth 1, then fetch (objectstack#22034)", () => {
type Step = { name?: string; uses?: string; with?: Record<string, unknown>; 'timeout-minutes'?: number; run?: string; env?: Record<string, string> };
const jobs = (parseYaml(rootCi()) as { jobs: Record<string, { 'timeout-minutes'?: number; steps: Step[] }> }).jobs;
const FETCH = "Fetch this commit's history and the base branch";
// Each job's first step that reads history: the fetch must come before it.
const FIRST_READER: Record<string, string> = {
'test-plan': "Plan this run's Test Core shards",
test: "Compute this shard's package set",
[UI_JOBS.test]: 'Select the tests this change affects',
[UI_JOBS.typeCheck]: 'check:lockfile-integrity — compare this pull request\'s lockfile with its merge base',
};
for (const [job, reader] of Object.entries(FIRST_READER)) {
it(`${job}: depth-1 checkout, the fetch step next, then the first reader`, () => {
const steps = jobs[job]?.steps ?? [];
expect(steps.length, `ci.yml has no job ${job}`).toBeGreaterThan(0);
const checkout = steps.findIndex((s) => s.uses?.startsWith('actions/checkout@'));
expect(checkout, `${job} has no actions/checkout step`).toBeGreaterThan(-1);
expect(steps[checkout].with?.['fetch-depth'], `${job}'s checkout sets fetch-depth`).toBeUndefined();
expect(steps[checkout + 1]?.name, `${job}: the step after the checkout is not the fetch`).toBe(FETCH);
const first = steps.findIndex((s) => s.name === reader);
expect(first, `${job} has no step named ${reader}`).toBeGreaterThan(checkout + 1);
// Each job sizes its own budget inside its wall (the `test` job's FETCH
// BUDGET comment): never under the healthy floor, never the whole wall.
const budget = steps[checkout + 1]['timeout-minutes'];
const wall = jobs[job]['timeout-minutes'];
expect(typeof budget, `${job}'s fetch step has no timeout-minutes`).toBe('number');
expect(budget).toBeGreaterThanOrEqual(8);
expect(typeof wall, `${job} has no job wall`).toBe('number');
expect(budget!).toBeLessThan(wall!);
});
}
it('the fetch step is one step, the same in all four jobs but for its budget', () => {
const copies = Object.keys(FIRST_READER).map((job) => {
const copy: Step = { ...jobs[job].steps.find((s) => s.name === FETCH) };
delete copy['timeout-minutes'];
return copy;
});
expect(copies[0]).toHaveProperty('run');
for (const copy of copies) expect(copy).toEqual(copies[0]);
expect(copies[0]?.run).toContain('git fetch --no-tags "${deepen[@]}" origin "$head" "${refspecs[@]}"');
});
});