diff --git a/README.md b/README.md index c35d22a..7b9b3fb 100644 --- a/README.md +++ b/README.md @@ -297,7 +297,7 @@ How a missing expectation is treated depends on the harness: - `commandJudgePreset` without a `test` option checks whatever expectations exist, and a test case with neither only has to run within the limits. A `test` option replaces that comparison; it receives `testCase.output`, `testCase.fileOutputPath` and `cwd` and can call the exported `judgeAgainstExpectations` (or `compareStdoutAsSpaceSeparatedTokens` and `compareExpectedOutputFiles`). A custom `readTestCases` may return any test case type with `id` (plus optional `input` and `fileInputPath`); the default verdict judges any case that exposes a string `output` or `fileOutputPath`, which the default reader's `CommandTestCase` does. - `guiCommandJudgePreset` passes the expectations to the problem's `test`, which decides everything. - `llmJudgePreset` runs no program, so it copies no `.fin/`; it hands `.in` as the prompt input and the whole entry (including `fileOutputPath`) to the problem's `test`. -- `stdioDebugPreset` by default copies the answer directory to a temporary directory and builds and runs it there together with `_shared.fin/` and the first example case's `.fin/` (the case's files win; hidden cases' inputs are never handed to learner code), so the answer directory is left untouched (its `node_modules`, and those of its ancestors, are linked into the copy rather than duplicated); files the program writes are reported only through `requiredOutputFilePaths`. Callers that already own a disposable answer directory can pass `{ disposableWorkingDirectory: true }` as the second argument to build and run directly there; they must remove it themselves, including when the harness is terminated. +- `stdioDebugPreset` by default copies the answer directory to a temporary directory and builds and runs it there together with `_shared.fin/` and the `.fin/` of the first example case that has input files (the case's files win; hidden cases' inputs are never handed to learner code), so the answer directory is left untouched (its `node_modules`, and those of its ancestors, are linked into the copy rather than duplicated); files the program writes are reported only through `requiredOutputFilePaths`. Callers that already own a disposable answer directory can pass `{ disposableWorkingDirectory: true }` as the second argument to build and run directly there; they must remove it themselves, including when the harness is terminated. - `evaluationJudgePreset` does not use `test_cases/`. `readTestCases` is exported for harnesses that enumerate `test_cases/` themselves. diff --git a/packages/problem-utils/src/helpers/selectDebugInputFilePaths.ts b/packages/problem-utils/src/helpers/selectDebugInputFilePaths.ts index 1b9eab0..ffa9cd9 100644 --- a/packages/problem-utils/src/helpers/selectDebugInputFilePaths.ts +++ b/packages/problem-utils/src/helpers/selectDebugInputFilePaths.ts @@ -19,27 +19,25 @@ const FILE_INPUT_EXTENSION = '.fin'; * @returns The selected paths, in the given order. */ export function selectDebugInputFilePaths(problemFilePaths: readonly string[]): string[] { - const pathToTestCaseId = new Map(); - for (const filePath of problemFilePaths) { - const [directoryName, entryName, ...rest] = path.posix.normalize(filePath).split('/'); - if (directoryName !== TEST_CASES_DIRECTORY_NAME || !entryName?.endsWith(FILE_INPUT_EXTENSION)) continue; - if (rest.length === 0) continue; - pathToTestCaseId.set(filePath, entryName.slice(0, -FILE_INPUT_EXTENSION.length)); - } - const selectedIds = new Set(selectDebugFileInputTestCaseIds(pathToTestCaseId.values())); + const fileInputTestCaseIds = new Set( + problemFilePaths.flatMap((filePath) => parseFileInputTestCaseId(filePath) ?? []) + ); + const exampleId = [...fileInputTestCaseIds] + .toSorted() + .find((id) => id !== SHARED_TEST_CASE_ID && EXAMPLE_TEST_CASE_ID_PATTERN.test(id)); return problemFilePaths.filter((filePath) => { - const id = pathToTestCaseId.get(filePath); - return id !== undefined && selectedIds.has(id); + const id = parseFileInputTestCaseId(filePath); + return id === SHARED_TEST_CASE_ID || (id !== undefined && id === exampleId); }); } /** - * The ids of the `test_cases/.fin/` directories a debug run receives, in the order they are copied - * (later ones overwrite earlier ones), given the ids of every such directory (`_shared` included). + * The test case id of a problem-relative path of a file inside a `test_cases/.fin/` directory, + * or `undefined` for any other path. */ -export function selectDebugFileInputTestCaseIds(fileInputTestCaseIds: Iterable): string[] { - const ids = [...new Set(fileInputTestCaseIds)].toSorted(); - const sharedIds = ids.filter((id) => id === SHARED_TEST_CASE_ID); - const exampleId = ids.find((id) => id !== SHARED_TEST_CASE_ID && EXAMPLE_TEST_CASE_ID_PATTERN.test(id)); - return exampleId === undefined ? sharedIds : [...sharedIds, exampleId]; +export function parseFileInputTestCaseId(problemFilePath: string): string | undefined { + const [directoryName, entryName, ...rest] = path.posix.normalize(problemFilePath).split('/'); + if (directoryName !== TEST_CASES_DIRECTORY_NAME || !entryName?.endsWith(FILE_INPUT_EXTENSION)) return; + if (rest.length === 0) return; + return entryName.slice(0, -FILE_INPUT_EXTENSION.length); } diff --git a/packages/problem-utils/src/presets/stdio.ts b/packages/problem-utils/src/presets/stdio.ts index 4fc4baa..157dc99 100644 --- a/packages/problem-utils/src/presets/stdio.ts +++ b/packages/problem-utils/src/presets/stdio.ts @@ -18,7 +18,7 @@ import { readProblemMarkdownFrontMatter, } from '../helpers/readProblemMarkdownFrontMatter.js'; import { readTestCases, SHARED_TEST_CASE_ID } from '../helpers/readTestCases.js'; -import { selectDebugFileInputTestCaseIds } from '../helpers/selectDebugInputFilePaths.js'; +import { parseFileInputTestCaseId, selectDebugInputFilePaths } from '../helpers/selectDebugInputFilePaths.js'; import { spawnWithTimeout } from '../helpers/spawnWithTimeout.js'; import { MAX_STDOUT_LENGTH } from '../helpers/stdioJudgeRules.js'; import { @@ -259,8 +259,9 @@ async function hasExpectedFiles(fileOutputPath: string | undefined): Promise { const testCases = await readTestCases(path.join(problemDir, 'test_cases')); const idToFileInputPath = new Map( testCases.flatMap((testCase) => (testCase.fileInputPath ? [[testCase.id, testCase.fileInputPath] as const] : [])) ); - const hasCaseFileInput = idToFileInputPath.size > 0; if (testCases.shared?.fileInputPath) idToFileInputPath.set(SHARED_TEST_CASE_ID, testCases.shared.fileInputPath); - const ids = selectDebugFileInputTestCaseIds(idToFileInputPath.keys()); - for (const id of ids) { + const problemFilePaths = await listFileInputFilePaths(idToFileInputPath); + const selectedIds = new Set( + selectDebugInputFilePaths(problemFilePaths).flatMap((filePath) => parseFileInputTestCaseId(filePath) ?? []) + ); + const exampleId = [...selectedIds].find((id) => id !== SHARED_TEST_CASE_ID); + // The example's files go last so that they overwrite shared files at the same path, as in judging. + for (const id of [...selectedIds].toSorted((a, b) => Number(a === exampleId) - Number(b === exampleId))) { const fileInputPath = idToFileInputPath.get(id); if (fileInputPath) await copyTestCaseFileInput(fileInputPath, cwd); } - if (hasCaseFileInput && ids.every((id) => id === SHARED_TEST_CASE_ID)) { + const hasCaseFileInput = problemFilePaths.some( + (filePath) => parseFileInputTestCaseId(filePath) !== SHARED_TEST_CASE_ID + ); + if (exampleId === undefined && hasCaseFileInput) { console.error('debug: no example test case has input files, so the program runs without them'); } } + +async function listFileInputFilePaths(idToFileInputPath: ReadonlyMap): Promise { + const problemFilePaths: string[] = []; + for (const [id, fileInputPath] of idToFileInputPath) { + const dirents = await fs.promises.readdir(fileInputPath, { recursive: true, withFileTypes: true }); + for (const dirent of dirents) { + if (dirent.isDirectory()) continue; + const pathInFileInput = path.relative(fileInputPath, path.join(dirent.parentPath, dirent.name)); + problemFilePaths.push(`test_cases/${id}.fin/${pathInFileInput}`); + } + } + return problemFilePaths; +} diff --git a/test/e2e/stdioDebugInputFiles.test.ts b/test/e2e/stdioDebugInputFiles.test.ts index e9441a3..b0fd6c6 100644 --- a/test/e2e/stdioDebugInputFiles.test.ts +++ b/test/e2e/stdioDebugInputFiles.test.ts @@ -41,36 +41,60 @@ test( selectDebugInputFilePaths(['./test_cases/example_2.fin/visible.txt', './test_cases/test_1.fin/secret.txt']) ).toEqual(['./test_cases/example_2.fin/visible.txt']); - await fs.mkdir('.tmp', { recursive: true }); - const root = await fs.mkdtemp(path.resolve('.tmp/stdio-debug-input-')); - try { - for (const [filePath, data] of Object.entries(problemFiles)) { - await fs.mkdir(path.dirname(path.join(root, filePath)), { recursive: true }); - await fs.writeFile(path.join(root, filePath), data); - } - const answer = path.join(root, 'answer'); - await fs.mkdir(answer); - await fs.writeFile( - path.join(answer, 'main.js'), - String.raw`import fs from 'node:fs'; console.log(fs.readdirSync('.', { recursive: true }).filter((p) => p !== 'main.js' && fs.statSync(p).isFile()).toSorted().map((p) => p + '=' + fs.readFileSync(p, 'utf8').trim()).join('\n'));` - ); - await fs.writeFile( - path.join(root, 'debug.ts'), - `import { stdioDebugPreset } from ${JSON.stringify(path.resolve('packages/problem-utils/src/presets/stdio.ts'))};\nawait stdioDebugPreset(import.meta.dirname);\n` - ); - const run = childProcess.spawnSync('bun', ['run', 'debug.ts', answer, JSON.stringify({ stdin: '' })], { - cwd: root, - encoding: 'utf8', - timeout: 20_000, - }); - expect(run.status, run.stderr).toBe(0); - const line = run.stdout.split('\n').find((value) => value.startsWith(TEST_CASE_RESULT_PREFIX)); - expect(line).toBeDefined(); - const result = testCaseResultSchema.parse(JSON.parse(line!.slice(TEST_CASE_RESULT_PREFIX.length))); - // The example's files overwrite the shared ones at the same path, as in judging. - expect(result.stdout).toBe('members.csv=example 2 members\nnested/notes.txt=shared\nvisible.txt=example 2\n'); - } finally { - await fs.rm(root, { recursive: true, force: true }); - } + // The example's files overwrite the shared ones at the same path, as in judging. + expect(await runDebug(problemFiles)).toBe( + 'members.csv=example 2 members\nnested/notes.txt=shared\nvisible.txt=example 2\n' + ); + } +); + +test( + 'a debug run skips an example whose input directory is empty, as selectDebugInputFilePaths does', + { timeout: 30_000 }, + async () => { + const files = { + 'problem.md': '---\n---\n', + 'test_cases/example_2.fin/visible.txt': 'example 2\n', + 'test_cases/test_1.fin/secret.txt': 'hidden\n', + }; + expect(selectDebugInputFilePaths(Object.keys(files))).toEqual(['test_cases/example_2.fin/visible.txt']); + // Git cannot track an empty directory, so only the fixture can create one. + expect(await runDebug(files, ['test_cases/example_1.fin'])).toBe('visible.txt=example 2\n'); } ); + +async function runDebug( + problemFiles: Record, + emptyDirectories: readonly string[] = [] +): Promise { + await fs.mkdir('.tmp', { recursive: true }); + const root = await fs.mkdtemp(path.resolve('.tmp/stdio-debug-input-')); + try { + for (const [filePath, data] of Object.entries(problemFiles)) { + await fs.mkdir(path.dirname(path.join(root, filePath)), { recursive: true }); + await fs.writeFile(path.join(root, filePath), data); + } + for (const directory of emptyDirectories) await fs.mkdir(path.join(root, directory), { recursive: true }); + const answer = path.join(root, 'answer'); + await fs.mkdir(answer); + await fs.writeFile( + path.join(answer, 'main.js'), + String.raw`import fs from 'node:fs'; console.log(fs.readdirSync('.', { recursive: true }).filter((p) => p !== 'main.js' && fs.statSync(p).isFile()).toSorted().map((p) => p + '=' + fs.readFileSync(p, 'utf8').trim()).join('\n'));` + ); + await fs.writeFile( + path.join(root, 'debug.ts'), + `import { stdioDebugPreset } from ${JSON.stringify(path.resolve('packages/problem-utils/src/presets/stdio.ts'))};\nawait stdioDebugPreset(import.meta.dirname);\n` + ); + const run = childProcess.spawnSync('bun', ['run', 'debug.ts', answer, JSON.stringify({ stdin: '' })], { + cwd: root, + encoding: 'utf8', + timeout: 20_000, + }); + expect(run.status, run.stderr).toBe(0); + const line = run.stdout.split('\n').find((value) => value.startsWith(TEST_CASE_RESULT_PREFIX)); + expect(line).toBeDefined(); + return testCaseResultSchema.parse(JSON.parse(line!.slice(TEST_CASE_RESULT_PREFIX.length))).stdout; + } finally { + await fs.rm(root, { recursive: true, force: true }); + } +}