An open source design system that's fully customizable and agent ready
TypeScript
test(cli): search goldens and the readme probe read the catalog once (#10273)
Christopher Chedeau3c7d1b2f3b30
diff --git a/packages/cli/foundation/discovery/component-discovery.readme.test.mjs b/packages/cli/foundation/discovery/component-discovery.readme.test.mjsindex bd482926e9..f5437c57b0 100644--- a/packages/cli/foundation/discovery/component-discovery.readme.test.mjs+++ b/packages/cli/foundation/discovery/component-discovery.readme.test.mjs@@ -25,25 +25,64 @@ const CORE = path.resolve('../../../core',);+/**+ * Where `findComponentReadme` found the doc for `name`: in the name's own+ * folder, in a parent folder, as its family's doc, or nowhere.+ * @param {string} name+ * @param {string | null} doc+ * @returns {string}+ */+function matchKind(name, doc) {+ if (doc == null) return 'none';+ const parts = path.relative(path.join(CORE, 'src'), doc).split(path.sep);+ const file = parts.at(-1);+ const isOwn = file === `${name}.doc.mjs` || file === `XDS${name}.doc.mjs`;+ if (parts.length === 2 && parts[0] === name && isOwn) return 'own folder';+ if (parts.length === 3 && parts[1] === name && isOwn) return 'nested';+ if (parts.length === 2 && isOwn) return 'parent folder';+ return 'family doc';+}+describe('findComponentReadme inside an operation', () => {- it('finds the doc it finds outside one, for a sample of Core names', () => {- // Every eighth name keeps the probes outside an operation short.- const names = Object.values(discoverComponents(CORE))- .flat()- .sort()- .filter((_, index) => index % 8 === 0);- const sample = [- ...names,- ...names.map(name => name.toLowerCase()),- ...names.map(name => `XDS${name}`),- 'Nope',- ];- const outside = sample.map(name => findComponentReadme(CORE, name));+ it('finds the doc it finds outside one, for a Core name of each kind of match', () => {+ const names = Object.values(discoverComponents(CORE)).flat().sort();+ /** @type {Record<string, (name: string) => string>} */+ const forms = {+ name: name => name,+ lowercase: name => name.toLowerCase(),+ prefixed: name => `XDS${name}`,+ };+ const queries = Object.entries(forms).flatMap(([form, spell]) =>+ names.map(name => ({form, name: spell(name)})),+ );+ queries.push({form: 'absent', name: 'Nope'});const inside = withListingCache(() =>- sample.map(name => findComponentReadme(CORE, name)),+ queries.map(({name}) => findComponentReadme(CORE, name)),);expect(inside.filter(Boolean).length).toBeGreaterThan(20);- expect(inside).toEqual(outside);+ // Outside an operation every probe reads the disk again, so one query of+ // each form and kind of match stands for the rest there.+ /** @type {Map<string, number>} */+ const firstOfKind = new Map();+ queries.forEach(({form, name}, index) => {+ const kind = `${form}: ${matchKind(name, inside[index])}`;+ if (!firstOfKind.has(kind)) firstOfKind.set(kind, index);+ });+ expect([...firstOfKind.keys()]).toEqual(+ expect.arrayContaining([+ 'name: own folder',+ 'name: parent folder',+ 'name: family doc',+ 'lowercase: none',+ 'prefixed: none',+ 'absent: none',+ ]),+ );+ for (const index of firstOfKind.values()) {+ expect(findComponentReadme(CORE, queries[index].name)).toBe(+ inside[index],+ );+ }});it('keeps the first folder in listing order when several hold the name', () => {diff --git a/packages/cli/test-utils/run-cli-sequence.mjs b/packages/cli/test-utils/run-cli-sequence.mjsnew file mode 100644index 0000000000..f1b07d8e8b--- /dev/null+++ b/packages/cli/test-utils/run-cli-sequence.mjs@@ -0,0 +1,120 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Runs a list of CLI invocations in one new process.+ *+ * @input A project folder, the argument lists to run there in order, and the+ * environment for the process.+ * @output One promise per invocation. Each resolves to that run's `runCli`+ * result (`{status, code, stdout, stderr}`) when the run ends.+ * @position Test helper. A suite runs a project's reads here when no read for+ * another project may answer them. The reads share the process, so the CLI+ * loads its catalog once for all of them.+ */++import {spawn} from 'node:child_process';+import * as fs from 'node:fs';+import {fileURLToPath} from 'node:url';++const SELF = fileURLToPath(import.meta.url);++/** The process writes each result to this descriptor, as one JSON line. */+const RESULTS_FD = 3;++/**+ * @typedef {{status: number, code: number, stdout: string, stderr: string}} CliResult+ */++/**+ * Promises for the `count` results that `lines` brings, one JSON line each.+ * A line that does not parse rejects only its own result.+ * @param {import('node:stream').Readable} lines+ * @param {number} count+ * @returns {{results: Promise<CliResult>[], rejectRest: (error: (done: number) => Error) => void}}+ * `rejectRest` rejects each result no line has settled yet.+ */+export function resultsFromLines(lines, count) {+ /** @type {{resolve: (result: CliResult) => void, reject: (error: Error) => void}[]} */+ const settlers = [];+ const results = Array.from(+ {length: count},+ () =>+ /** @type {Promise<CliResult>} */ (+ new Promise((resolve, reject) => settlers.push({resolve, reject}))+ ),+ );+ // A result that no test awaits yet must not count as an unhandled+ // rejection.+ for (const result of results) result.catch(() => {});+ let done = 0;+ let unread = '';+ lines.setEncoding('utf8').on('data', chunk => {+ unread += chunk;+ for (let end = unread.indexOf('\n'); end >= 0; end = unread.indexOf('\n')) {+ const line = unread.slice(0, end);+ unread = unread.slice(end + 1);+ const settler = settlers[done];+ done += 1;+ try {+ settler?.resolve(JSON.parse(line));+ } catch {+ settler?.reject(+ new Error(`Run ${done} wrote a line that is not JSON: ${line}`),+ );+ }+ }+ });+ return {+ results,+ rejectRest: error => {+ for (const {reject} of settlers.slice(done)) reject(error(done));+ },+ };+}++/**+ * Starts one process that runs `invocations` in `cwd`, in order. A test that+ * awaits a later result also waits for every run before it, even when a+ * filter skips the tests that read those runs.+ * @param {string} cwd+ * @param {string[][]} invocations+ * @param {NodeJS.ProcessEnv} env+ * @returns {{results: Promise<CliResult>[], stop: () => void}}+ */+export function startCliSequence(cwd, invocations, env) {+ const child = spawn(+ process.execPath,+ [SELF, cwd, JSON.stringify(invocations)],+ {env, stdio: ['ignore', 'ignore', 'pipe', 'pipe']},+ );+ let stderr = '';+ child.stderr?.setEncoding('utf8').on('data', chunk => (stderr += chunk));+ const {results, rejectRest} = resultsFromLines(+ /** @type {import('node:stream').Readable} */ (child.stdio[RESULTS_FD]),+ invocations.length,+ );+ child.on('close', code =>+ rejectRest(+ done =>+ new Error(+ `The CLI process ended (${code}) after ${done} of ${invocations.length} runs.\n${stderr}`,+ ),+ ),+ );+ return {results, stop: () => child.kill()};+}++/** Runs the invocations named on the command line, one after another. */+async function main() {+ const cwd = process.argv[2];+ const invocations = JSON.parse(process.argv[3]);+ const {runCli} = await import('./run-cli.mjs');+ for (const args of invocations) {+ const result = await runCli(args, cwd);+ fs.writeSync(RESULTS_FD, `${JSON.stringify(result)}\n`);+ }+ // A handle the CLI leaves open must not keep this process alive.+ process.exit(0);+}++if (process.argv[1] === SELF) await main();diff --git a/packages/cli/test-utils/run-cli-sequence.test.mjs b/packages/cli/test-utils/run-cli-sequence.test.mjsnew file mode 100644index 0000000000..3ae3fecf40--- /dev/null+++ b/packages/cli/test-utils/run-cli-sequence.test.mjs@@ -0,0 +1,48 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {PassThrough} from 'node:stream';+import {runCli} from './run-cli.mjs';+import {resultsFromLines, startCliSequence} from './run-cli-sequence.mjs';++const ENV = {...process.env, NO_COLOR: '1', FORCE_COLOR: '0'};++describe('startCliSequence', () => {+ it('gives each invocation the result runCli gives in this process', async () => {+ const cwd = os.tmpdir();+ const invocations = [['--version'], ['no-such-command']];+ const {results} = startCliSequence(cwd, invocations, ENV);+ for (const [index, args] of invocations.entries()) {+ const expected = await runCli(args, cwd);+ const actual = await results[index];+ expect({status: actual.status, stdout: actual.stdout}).toEqual({+ status: expected.status,+ stdout: expected.stdout,+ });+ }+ });++ it('rejects the runs the process did not finish, with its error output', async () => {+ const missing = path.join(os.tmpdir(), 'astryx-no-such-folder');+ fs.rmSync(missing, {recursive: true, force: true});+ const {results} = startCliSequence(missing, [['--version']], ENV);+ await expect(results[0]).rejects.toThrow(/after 0 of 1 runs[\s\S]*ENOENT/u);+ });+});++describe('resultsFromLines', () => {+ it('rejects only the result whose line is not JSON', async () => {+ const lines = new PassThrough();+ const {results} = resultsFromLines(lines, 3);+ lines.write('{"status":0,"code":0,"stdout":"first","stderr":""}\nnot');+ lines.write(' JSON\n{"status":1,"code":1,"stdout":"","stderr":"third"}\n');+ await expect(results[0]).resolves.toMatchObject({stdout: 'first'});+ await expect(results[1]).rejects.toThrow(+ 'Run 2 wrote a line that is not JSON: not JSON',+ );+ await expect(results[2]).resolves.toMatchObject({stderr: 'third'});+ });+});diff --git a/packages/cli/test/experimental-isolation.test.mjs b/packages/cli/test/experimental-isolation.test.mjsindex 81144a6518..a75f3517d3 100644--- a/packages/cli/test/experimental-isolation.test.mjs+++ b/packages/cli/test/experimental-isolation.test.mjs@@ -48,6 +48,7 @@ import {createHash} from 'node:crypto';import {pathToFileURL} from 'node:url';import {CLI_ROOT} from '../foundation/fs/paths.mjs';import {runCli} from '../test-utils/run-cli.mjs';+import {startCliSequence} from '../test-utils/run-cli-sequence.mjs';import {writeIconSetProject} from '../test-utils/icon-set-fixture.mjs';const REPO_ROOT = path.resolve(CLI_ROOT, '..', '..');@@ -179,6 +180,14 @@ const PROJECTS_ROOT = REGENERATING ? GOLDEN_REPO : REPO_ROOT;/** @type {string} */let project;+/** The environment the CLI runs in. */+const CLI_ENV = {+ ...process.env,+ NO_COLOR: '1',+ FORCE_COLOR: '0',+ COLUMNS: '100',+};+/*** Run the CLI in the project; machine paths and the CLI's release version* become placeholders.@@ -188,7 +197,7 @@ function astryx(args, cwd = project) {const result = spawnSync(process.execPath, [CLI_BIN, ...args], {cwd,encoding: 'utf8',- env: {...process.env, NO_COLOR: '1', FORCE_COLOR: '0', COLUMNS: '100'},+ env: CLI_ENV,});// A golden is main's own answer, never one main handed to this checkout.if (REGENERATING && /handed over from CLI/u.test(result.stderr)) {@@ -403,6 +412,32 @@ function textShape(text, keep = []) {return out.join('\n');}+/**+ * One CLI run for a golden. Outside regeneration it runs in this process, as+ * the docs topics do. So the runs share one read of the catalog, and no run+ * starts a new process.+ * @param {string[]} args+ * @param {string} cwd+ */+async function cliRun(args, cwd) {+ if (REGENERATING) return astryx(args, cwd);+ const result = await runCli(args, cwd);+ return {+ status: result.status,+ stdout: placeholders(result.stdout, cwd),+ stderr: placeholders(result.stderr, cwd),+ };+}++/**+ * The arguments of `astryx search <query>`, for JSON or for text.+ * @param {string} query+ * @param {boolean} json+ */+function searchArgs(query, json) {+ return ['search', ...query.split(' '), ...(json ? ['--json'] : [])];+}+/*** `astryx search` as a golden: the count, and each result's identity and* order, with the sentences that name an experimental surface (the stable@@ -410,9 +445,10 @@ function textShape(text, keep = []) {* an icon, or an icon definition.* @param {string} query* @param {string} cwd+ * @param {typeof cliRun} [run] how the CLI runs: in this process by default*/-function searchGolden(query, cwd) {- const json = astryx(['search', ...query.split(' '), '--json'], cwd);+async function searchGolden(query, cwd, run = cliRun) {+ const json = await run(searchArgs(query, true), cwd);expect(json.status).toBe(0);const body = JSON.parse(json.stdout);// The one stable addition FR18 makes: the field reference's `stability`@@ -436,7 +472,7 @@ function searchGolden(query, cwd) {...skeleton(result),mentions: leakMentions(result),}));- const text = astryx(['search', ...query.split(' ')], cwd);+ const text = await run(searchArgs(query, false), cwd);// The same addition left out of the text: its block, and its count.const blocks = text.stdout.split('\n\n')@@ -516,11 +552,7 @@ describe('with no icon set, stable output is unchanged', () => {// instead of a new process per topic. Those runs print what the bin// prints, as the listing checks./** @param {string[]} args */- const read = async args => {- if (REGENERATING) return astryx(args);- const result = await runCli(args, project);- return {...result, stdout: placeholders(result.stdout, project)};- };+ const read = args => cliRun(args, project);expect((await read(['docs', '--json'])).stdout).toBe(listed.stdout);const list = JSON.parse(listed.stdout);/** @type {Record<string, any>} */@@ -747,7 +779,7 @@ describe('with no icon set, stable output is unchanged', () => {'icon set',])('search %s, text and JSON', async query => {const slug = query.replace(/\s+/g, '-');- const {json, text} = searchGolden(query, project);+ const {json, text} = await searchGolden(query, project);await expect(json).toMatchFileSnapshot(path.join(GOLDEN, `search-${slug}.json`),);@@ -756,6 +788,16 @@ describe('with no icon set, stable output is unchanged', () => {);});+ it('an in-process search prints what the bin prints', async () => {+ const args = ['search', 'close', '--json'];+ const bin = astryx(args);+ const inProcess = await cliRun(args, project);+ expect({status: inProcess.status, stdout: inProcess.stdout}).toEqual({+ status: bin.status,+ stdout: bin.stdout,+ });+ });+it('search --type icon is an unknown type, offering only the stable domains', async () => {const res = astryx(['search', 'trash', '--type', 'icon', '--json']);expect(res.status).toBe(1);@@ -989,10 +1031,23 @@ export default {describe.skipIf(REGENERATING)('with an icon set installed and configured, search is unchanged',() => {+ const queries = [+ 'delete',+ 'close',+ 'trash can',+ 'experimental',+ 'icon set',+ ];/** @type {string} */let root;/** @type {string} */let withSet;+ /**+ * Each search's result from the process that runs them, by its arguments.+ * @type {Map<string, Promise<import('../test-utils/run-cli-sequence.mjs').CliResult>>}+ */+ const searches = new Map();+ let stopSearches = () => {};beforeAll(() => {root = fs.mkdtempSync(path.join(PROJECTS_ROOT, '.astryx-icon-set-search-'),@@ -1007,11 +1062,39 @@ describe.skipIf(REGENERATING)(path.join(withSet, 'node_modules', '.bin', 'astryx'),'',);+ // One new process runs every search here, so nothing this process read+ // for the project without icon sets can answer for this one. The+ // searches share that process, so the CLI reads the catalog once.+ const invocations = queries.flatMap(query => [+ searchArgs(query, true),+ searchArgs(query, false),+ ]);+ const sequence = startCliSequence(withSet, invocations, CLI_ENV);+ invocations.forEach((args, index) =>+ searches.set(args.join(' '), sequence.results[index]),+ );+ stopSearches = sequence.stop;});afterAll(() => {+ stopSearches();fs.rmSync(root, {recursive: true, force: true});});+ /**+ * A search's result from the process that runs the searches.+ * @param {string[]} args+ * @param {string} cwd+ */+ async function search(args, cwd) {+ const result = await searches.get(args.join(' '));+ if (!result) throw new Error(`No search runs \`${args.join(' ')}\`.`);+ return {+ status: result.status,+ stdout: placeholders(result.stdout, cwd),+ stderr: placeholders(result.stderr, cwd),+ };+ }+it('the set is loaded', () => {const list = JSON.parse(astryx(['experimental', 'icon', '--list', '--json'], withSet).stdout,@@ -1021,11 +1104,11 @@ describe.skipIf(REGENERATING)(// Icon words: icon lookup by meaning is only `astryx experimental icon`;// `astryx search` joins it only at promotion (spec:AST-084 FR11).- it.each(['delete', 'close', 'trash can', 'experimental', 'icon set'])(+ it.each(queries)('search %s equals the output without icon sets, text and JSON',async query => {const slug = query.replace(/\s+/g, '-');- const {json, text} = searchGolden(query, withSet);+ const {json, text} = await searchGolden(query, withSet, search);await expect(json).toMatchFileSnapshot(path.join(GOLDEN, `search-${slug}.json`),);@@ -1035,6 +1118,16 @@ describe.skipIf(REGENERATING)(},);+ it('a search in that process prints what the bin prints', async () => {+ const args = searchArgs('close', true);+ const bin = astryx(args, withSet);+ const inProcess = await search(args, withSet);+ expect({status: inProcess.status, stdout: inProcess.stdout}).toEqual({+ status: bin.status,+ stdout: bin.stdout,+ });+ });+it('search --type icon stays an unknown type', () => {const res = astryx(['search', 'trash', '--type', 'icon', '--json'],