@rickycourtes/mdtest 0.0.0-stage → 0.1.0
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.
- package/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.md +295 -2
- package/bin/mdtest.js +12 -0
- package/package.json +54 -4
- package/schema.json +80 -0
- package/src/claude.js +161 -0
- package/src/cli.js +118 -0
- package/src/discover.js +172 -0
- package/src/index.js +6 -0
- package/src/init.js +110 -0
- package/src/parse.js +137 -0
- package/src/reporter.js +158 -0
- package/src/run.js +182 -0
package/src/reporter.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// Jest-style terminal output.
|
|
2
|
+
|
|
3
|
+
/** @param {NodeJS.WriteStream | { isTTY?: boolean }} stream */
|
|
4
|
+
export function colors(stream = process.stdout) {
|
|
5
|
+
const on = !process.env.NO_COLOR && (Boolean(process.env.FORCE_COLOR) || Boolean(stream.isTTY));
|
|
6
|
+
const wrap = (open, close) => (s) => (on ? `\x1b[${open}m${s}\x1b[${close}m` : String(s));
|
|
7
|
+
return {
|
|
8
|
+
bold: wrap(1, 22), dim: wrap(2, 22), red: wrap(31, 39), green: wrap(32, 39),
|
|
9
|
+
yellow: wrap(33, 39), magenta: wrap(35, 39), cyan: wrap(36, 39),
|
|
10
|
+
passBadge: wrap('1;30;42', '0'), failBadge: wrap('1;37;41', '0'), runBadge: wrap('1;30;43', '0'),
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const time = (ms) => (ms >= 1000 ? `${(ms / 1000).toFixed(1)} s` : `${ms} ms`);
|
|
15
|
+
const money = (usd) => `$${usd.toFixed(usd < 1 ? 4 : 2)}`;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {{ write?: (s: string) => void, verbose?: boolean, color?: ReturnType<typeof colors> }} [opts]
|
|
19
|
+
* @returns {import('./run.js').Reporter}
|
|
20
|
+
*/
|
|
21
|
+
export function defaultReporter(opts = {}) {
|
|
22
|
+
const write = opts.write ?? ((s) => process.stdout.write(s));
|
|
23
|
+
const c = opts.color ?? colors();
|
|
24
|
+
const out = (line = '') => write(`${line}\n`);
|
|
25
|
+
let fixMode = false;
|
|
26
|
+
|
|
27
|
+
return {
|
|
28
|
+
onStart({ files, fix }) {
|
|
29
|
+
fixMode = fix;
|
|
30
|
+
const count = files.reduce((n, f) => n + f.tests.length, 0);
|
|
31
|
+
if (!files.length) out(c.yellow('No Markdown tests found.'));
|
|
32
|
+
else if (fix) out(c.dim(`Fix mode: Claude will change code to make ${count} test(s) pass.\n`));
|
|
33
|
+
},
|
|
34
|
+
onTestStart(test) {
|
|
35
|
+
if (opts.verbose) out(`${c.runBadge(' RUNS ')} ${c.dim(test.file)} ${test.fullName}`);
|
|
36
|
+
},
|
|
37
|
+
onTestEvent(test, e) {
|
|
38
|
+
if (!opts.verbose) return;
|
|
39
|
+
const text = e.kind === 'tool' ? c.cyan(`› ${e.text}`) : c.dim(e.text.split('\n')[0].slice(0, 160));
|
|
40
|
+
out(` ${c.dim(test.name)} ${text}`);
|
|
41
|
+
},
|
|
42
|
+
onFileDone(file, results) {
|
|
43
|
+
const failed = results.some((r) => r.status === 'failed');
|
|
44
|
+
const ms = results.reduce((s, r) => s + r.durationMs, 0);
|
|
45
|
+
out(`${failed ? c.failBadge(' FAIL ') : c.passBadge(' PASS ')} ${c.dim(dirOf(file))}${c.bold(baseOf(file))} ${c.dim(`(${time(ms)})`)}`);
|
|
46
|
+
let shown = [];
|
|
47
|
+
for (const r of results) {
|
|
48
|
+
const path = r.test.path;
|
|
49
|
+
let i = 0;
|
|
50
|
+
while (i < path.length && shown[i] === path[i]) i++;
|
|
51
|
+
for (; i < path.length; i++) out(`${' '.repeat(i + 1)}${path[i]}`);
|
|
52
|
+
shown = path;
|
|
53
|
+
const pad = ' '.repeat(path.length + 1);
|
|
54
|
+
const extra = r.durationMs ? c.dim(` (${time(r.durationMs)})`) : '';
|
|
55
|
+
if (r.status === 'passed') out(`${pad}${c.green('✓')} ${c.dim(r.test.name)}${extra}`);
|
|
56
|
+
else if (r.status === 'failed') out(`${pad}${c.red('✕')} ${r.test.name}${extra}`);
|
|
57
|
+
else if (r.status === 'skipped') out(`${pad}${c.yellow('○')} ${c.dim(`skipped ${r.test.name}`)}`);
|
|
58
|
+
else out(`${pad}${c.magenta('✎')} ${c.dim(`todo ${r.test.name}`)}`);
|
|
59
|
+
if (fixMode && r.verdict?.changes?.length) {
|
|
60
|
+
for (const ch of r.verdict.changes) out(`${pad} ${c.cyan('±')} ${c.dim(ch)}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
for (const r of results.filter((x) => x.status === 'failed')) {
|
|
64
|
+
out();
|
|
65
|
+
out(c.red(c.bold(` ● ${r.test.fullName}`)));
|
|
66
|
+
out();
|
|
67
|
+
out(indent(r.verdict?.reason || r.error || 'Failed', ' '));
|
|
68
|
+
if (r.verdict?.evidence?.length) {
|
|
69
|
+
out();
|
|
70
|
+
for (const e of r.verdict.evidence) out(c.dim(` ${e}`));
|
|
71
|
+
}
|
|
72
|
+
out();
|
|
73
|
+
out(c.dim(` at ${r.test.file}:${r.test.line}`));
|
|
74
|
+
}
|
|
75
|
+
out();
|
|
76
|
+
},
|
|
77
|
+
onDone(summary) {
|
|
78
|
+
const files = summary.files.filter((f) => f.results.length);
|
|
79
|
+
const fileFailed = files.filter((f) => f.results.some((r) => r.status === 'failed')).length;
|
|
80
|
+
const fileSkipped = files.filter((f) => f.results.every((r) => r.status === 'skipped' || r.status === 'todo')).length;
|
|
81
|
+
const tally = (s) => summary.results.filter((r) => r.status === s).length;
|
|
82
|
+
const parts = (items, total) =>
|
|
83
|
+
[...items.filter(([n]) => n > 0).map(([n, label, paint]) => paint(`${n} ${label}`)), `${total} total`].join(', ');
|
|
84
|
+
|
|
85
|
+
out(`${c.bold('Test Suites:')} ${parts([
|
|
86
|
+
[fileFailed, 'failed', (s) => c.bold(c.red(s))],
|
|
87
|
+
[fileSkipped, 'skipped', (s) => c.bold(c.yellow(s))],
|
|
88
|
+
[files.length - fileFailed - fileSkipped, 'passed', (s) => c.bold(c.green(s))],
|
|
89
|
+
], files.length)}`);
|
|
90
|
+
out(`${c.bold('Tests: ')} ${parts([
|
|
91
|
+
[tally('failed'), 'failed', (s) => c.bold(c.red(s))],
|
|
92
|
+
[tally('skipped'), 'skipped', (s) => c.bold(c.yellow(s))],
|
|
93
|
+
[tally('todo'), 'todo', (s) => c.bold(c.magenta(s))],
|
|
94
|
+
[tally('passed'), 'passed', (s) => c.bold(c.green(s))],
|
|
95
|
+
], summary.results.length)}`);
|
|
96
|
+
out(`${c.bold('Time: ')} ${time(summary.durationMs)}`);
|
|
97
|
+
out(`${c.bold('Cost: ')} ${money(summary.costUsd)}`);
|
|
98
|
+
if (summary.bailed) out(c.dim('Bailed after the first failure.'));
|
|
99
|
+
out(c.dim('Ran all Markdown test suites.'));
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** @param {import('./parse.js').TestFile[]} files @param {ReturnType<typeof colors>} [c] */
|
|
105
|
+
export function formatList(files, c = colors()) {
|
|
106
|
+
const lines = [];
|
|
107
|
+
for (const f of files) {
|
|
108
|
+
lines.push(c.bold(f.file));
|
|
109
|
+
let shown = [];
|
|
110
|
+
for (const t of f.tests) {
|
|
111
|
+
let i = 0;
|
|
112
|
+
while (i < t.path.length && shown[i] === t.path[i]) i++;
|
|
113
|
+
for (; i < t.path.length; i++) lines.push(`${' '.repeat(i + 1)}${t.path[i]}`);
|
|
114
|
+
shown = t.path;
|
|
115
|
+
const tag = t.mode === 'run' ? '' : c.yellow(` [${t.mode}]`);
|
|
116
|
+
lines.push(`${' '.repeat(t.path.length + 1)}${c.dim('•')} ${t.name}${tag} ${c.dim(`:${t.line}`)}`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const count = files.reduce((n, f) => n + f.tests.length, 0);
|
|
120
|
+
lines.push('', c.dim(`${count} test(s) in ${files.length} file(s)`));
|
|
121
|
+
return lines.join('\n');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** @param {import('./run.js').RunSummary} summary */
|
|
125
|
+
export function toJSON(summary) {
|
|
126
|
+
const count = (s) => summary.results.filter((r) => r.status === s).length;
|
|
127
|
+
return {
|
|
128
|
+
success: summary.success,
|
|
129
|
+
numTotalTests: summary.results.length,
|
|
130
|
+
numPassedTests: count('passed'),
|
|
131
|
+
numFailedTests: count('failed'),
|
|
132
|
+
numPendingTests: count('skipped'),
|
|
133
|
+
numTodoTests: count('todo'),
|
|
134
|
+
durationMs: summary.durationMs,
|
|
135
|
+
costUsd: summary.costUsd,
|
|
136
|
+
testResults: summary.files.map((f) => ({
|
|
137
|
+
name: f.file,
|
|
138
|
+
status: f.results.some((r) => r.status === 'failed') ? 'failed' : 'passed',
|
|
139
|
+
assertionResults: f.results.map((r) => ({
|
|
140
|
+
title: r.test.name,
|
|
141
|
+
ancestorTitles: r.test.path,
|
|
142
|
+
fullName: r.test.fullName,
|
|
143
|
+
line: r.test.line,
|
|
144
|
+
status: r.status === 'skipped' ? 'pending' : r.status,
|
|
145
|
+
durationMs: r.durationMs,
|
|
146
|
+
costUsd: r.costUsd,
|
|
147
|
+
attempts: r.attempts,
|
|
148
|
+
reason: r.verdict?.reason ?? r.error,
|
|
149
|
+
evidence: r.verdict?.evidence ?? [],
|
|
150
|
+
...(r.verdict?.changes ? { changes: r.verdict.changes } : {}),
|
|
151
|
+
})),
|
|
152
|
+
})),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const dirOf = (f) => (f.includes('/') ? f.slice(0, f.lastIndexOf('/') + 1) : '');
|
|
157
|
+
const baseOf = (f) => f.slice(f.lastIndexOf('/') + 1);
|
|
158
|
+
const indent = (s, pad) => s.split('\n').map((l) => pad + l).join('\n');
|
package/src/run.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { parse } from './parse.js';
|
|
4
|
+
import { findTestFiles, loadConfig, readSetupFiles } from './discover.js';
|
|
5
|
+
import { verifyWithClaude } from './claude.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @typedef {import('./parse.js').TestCase} TestCase
|
|
9
|
+
* @typedef {import('./parse.js').TestFile} TestFile
|
|
10
|
+
* @typedef {'passed' | 'failed' | 'skipped' | 'todo'} Status
|
|
11
|
+
* @typedef {{
|
|
12
|
+
* test: TestCase, status: Status, durationMs: number, costUsd: number, attempts: number,
|
|
13
|
+
* verdict?: import('./claude.js').Verdict, error?: string,
|
|
14
|
+
* }} TestResult
|
|
15
|
+
* @typedef {{
|
|
16
|
+
* files: { file: string, results: TestResult[] }[], results: TestResult[],
|
|
17
|
+
* durationMs: number, costUsd: number, success: boolean, bailed: boolean,
|
|
18
|
+
* }} RunSummary
|
|
19
|
+
* @typedef {{
|
|
20
|
+
* onStart?: (info: { files: TestFile[], fix: boolean }) => void,
|
|
21
|
+
* onTestStart?: (test: TestCase) => void,
|
|
22
|
+
* onTestEvent?: (test: TestCase, event: { kind: string, text: string }) => void,
|
|
23
|
+
* onTestDone?: (result: TestResult) => void,
|
|
24
|
+
* onFileDone?: (file: string, results: TestResult[]) => void,
|
|
25
|
+
* onDone?: (summary: RunSummary) => void,
|
|
26
|
+
* }} Reporter
|
|
27
|
+
* @typedef {{
|
|
28
|
+
* rootDir?: string, configPath?: string, patterns?: string[], testNamePattern?: string, fix?: boolean, bail?: boolean,
|
|
29
|
+
* verbose?: boolean, verify?: import('./claude.js').Verifier, reporter?: Reporter,
|
|
30
|
+
* config?: Partial<import('./discover.js').Config>,
|
|
31
|
+
* }} RunOptions
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Finds and parses test files without running anything.
|
|
36
|
+
* @param {RunOptions} [options]
|
|
37
|
+
* @returns {Promise<{ config: import('./discover.js').Config, files: TestFile[] }>}
|
|
38
|
+
*/
|
|
39
|
+
export async function collect(options = {}) {
|
|
40
|
+
const config = await loadConfig(options.rootDir ?? process.cwd(), options.config, options.configPath);
|
|
41
|
+
const [paths, setup] = await Promise.all([findTestFiles(config, options.patterns), readSetupFiles(config)]);
|
|
42
|
+
const files = await Promise.all(
|
|
43
|
+
paths.map(async (p) => parse(await readFile(join(config.rootDir, p), 'utf8'), p)),
|
|
44
|
+
);
|
|
45
|
+
// Setup files are context for every test, ahead of the test file's own.
|
|
46
|
+
const shared = setup.map((s) => s.text);
|
|
47
|
+
if (shared.length) for (const f of files) for (const t of f.tests) t.context = [...shared, ...t.context];
|
|
48
|
+
if (options.testNamePattern) {
|
|
49
|
+
const re = new RegExp(options.testNamePattern, 'i');
|
|
50
|
+
for (const f of files) for (const t of f.tests) if (!re.test(t.fullName) && t.mode !== 'todo') t.mode = 'skip';
|
|
51
|
+
}
|
|
52
|
+
return { config, files };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param {RunOptions} [options]
|
|
57
|
+
* @returns {Promise<RunSummary>}
|
|
58
|
+
*/
|
|
59
|
+
export async function run(options = {}) {
|
|
60
|
+
const started = Date.now();
|
|
61
|
+
const { config, files } = await collect(options);
|
|
62
|
+
const verify = options.verify ?? verifyWithClaude;
|
|
63
|
+
const reporter = options.reporter ?? {};
|
|
64
|
+
const fix = Boolean(options.fix);
|
|
65
|
+
// Fixes edit the project, so they run one at a time.
|
|
66
|
+
const concurrency = fix ? 1 : Math.max(1, Number(config.concurrency) || 1);
|
|
67
|
+
const bail = new AbortController();
|
|
68
|
+
|
|
69
|
+
reporter.onStart?.({ files, fix });
|
|
70
|
+
|
|
71
|
+
/** @type {Map<string, TestResult[]>} */
|
|
72
|
+
const byFile = new Map(files.map((f) => [f.file, []]));
|
|
73
|
+
/** @type {Map<string, number>} */
|
|
74
|
+
const remaining = new Map(files.map((f) => [f.file, f.tests.length]));
|
|
75
|
+
const order = new Map(files.flatMap((f) => f.tests.map((t, i) => [t.id, i])));
|
|
76
|
+
|
|
77
|
+
/** @param {TestResult} result */
|
|
78
|
+
const finish = (result) => {
|
|
79
|
+
const list = /** @type {TestResult[]} */ (byFile.get(result.test.file));
|
|
80
|
+
list.push(result);
|
|
81
|
+
reporter.onTestDone?.(result);
|
|
82
|
+
const left = /** @type {number} */ (remaining.get(result.test.file)) - 1;
|
|
83
|
+
remaining.set(result.test.file, left);
|
|
84
|
+
if (left === 0) {
|
|
85
|
+
list.sort((a, b) => /** @type {number} */ (order.get(a.test.id)) - /** @type {number} */ (order.get(b.test.id)));
|
|
86
|
+
reporter.onFileDone?.(result.test.file, list);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
for (const f of files) if (f.tests.length === 0) reporter.onFileDone?.(f.file, []);
|
|
91
|
+
|
|
92
|
+
/** @type {{ test: TestCase, opts: TestFile['options'] }[]} */
|
|
93
|
+
const queue = [];
|
|
94
|
+
for (const f of files) {
|
|
95
|
+
for (const test of f.tests) {
|
|
96
|
+
if (test.mode === 'skip' || test.mode === 'todo') {
|
|
97
|
+
finish({ test, status: test.mode === 'todo' ? 'todo' : 'skipped', durationMs: 0, costUsd: 0, attempts: 0 });
|
|
98
|
+
} else queue.push({ test, opts: f.options });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const worker = async () => {
|
|
103
|
+
for (let job = queue.shift(); job; job = queue.shift()) {
|
|
104
|
+
const { test, opts } = job;
|
|
105
|
+
if (bail.signal.aborted) {
|
|
106
|
+
finish({ test, status: 'skipped', durationMs: 0, costUsd: 0, attempts: 0 });
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
reporter.onTestStart?.(test);
|
|
110
|
+
const result = await runOne(test, { ...config, ...pick(opts) }, verify, fix, bail.signal, reporter);
|
|
111
|
+
finish(result);
|
|
112
|
+
if (options.bail && result.status === 'failed') bail.abort();
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, worker));
|
|
116
|
+
|
|
117
|
+
const all = files.flatMap((f) => /** @type {TestResult[]} */ (byFile.get(f.file)));
|
|
118
|
+
/** @type {RunSummary} */
|
|
119
|
+
const summary = {
|
|
120
|
+
files: files.map((f) => ({ file: f.file, results: /** @type {TestResult[]} */ (byFile.get(f.file)) })),
|
|
121
|
+
results: all,
|
|
122
|
+
durationMs: Date.now() - started,
|
|
123
|
+
costUsd: all.reduce((s, r) => s + r.costUsd, 0),
|
|
124
|
+
success: all.every((r) => r.status !== 'failed'),
|
|
125
|
+
bailed: bail.signal.aborted,
|
|
126
|
+
};
|
|
127
|
+
reporter.onDone?.(summary);
|
|
128
|
+
return summary;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* @param {TestCase} test
|
|
133
|
+
* @param {import('./discover.js').Config} config
|
|
134
|
+
* @param {import('./claude.js').Verifier} verify
|
|
135
|
+
* @param {boolean} fix
|
|
136
|
+
* @param {AbortSignal} bailSignal
|
|
137
|
+
* @param {Reporter} reporter
|
|
138
|
+
* @returns {Promise<TestResult>}
|
|
139
|
+
*/
|
|
140
|
+
async function runOne(test, config, verify, fix, bailSignal, reporter) {
|
|
141
|
+
const started = Date.now();
|
|
142
|
+
let costUsd = 0;
|
|
143
|
+
let attempts = 0;
|
|
144
|
+
let last;
|
|
145
|
+
const tries = 1 + Math.max(0, Number(config.retries) || 0);
|
|
146
|
+
while (attempts < tries) {
|
|
147
|
+
attempts++;
|
|
148
|
+
const timeout = AbortSignal.timeout(Number(config.timeout));
|
|
149
|
+
const signal = AbortSignal.any([timeout, bailSignal]);
|
|
150
|
+
last = await verify(test, {
|
|
151
|
+
cwd: config.rootDir,
|
|
152
|
+
model: config.model,
|
|
153
|
+
effort: config.effort,
|
|
154
|
+
tools: config.tools,
|
|
155
|
+
maxTurns: config.maxTurns,
|
|
156
|
+
maxBudgetUsd: config.maxBudgetUsd,
|
|
157
|
+
fix,
|
|
158
|
+
signal,
|
|
159
|
+
onEvent: reporter.onTestEvent ? (e) => reporter.onTestEvent?.(test, e) : undefined,
|
|
160
|
+
}).catch((err) => ({ error: String(err?.message ?? err), costUsd: 0, turns: 0, durationMs: 0 }));
|
|
161
|
+
if (timeout.aborted) last = { ...last, verdict: undefined, error: `Timed out after ${config.timeout} ms` };
|
|
162
|
+
costUsd += last.costUsd ?? 0;
|
|
163
|
+
// Retry only when Claude could not reach a verdict, never to re-roll a failure.
|
|
164
|
+
if (last.verdict || bailSignal.aborted) break;
|
|
165
|
+
}
|
|
166
|
+
const verdict = last?.verdict;
|
|
167
|
+
return {
|
|
168
|
+
test,
|
|
169
|
+
status: verdict?.pass ? 'passed' : 'failed',
|
|
170
|
+
durationMs: Date.now() - started,
|
|
171
|
+
costUsd,
|
|
172
|
+
attempts,
|
|
173
|
+
...(verdict ? { verdict } : {}),
|
|
174
|
+
...(!verdict && last?.error ? { error: last.error } : {}),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Per-file frontmatter keys that may override the config. */
|
|
179
|
+
function pick(opts) {
|
|
180
|
+
const keys = ['model', 'effort', 'timeout', 'maxTurns', 'maxBudgetUsd', 'tools', 'retries'];
|
|
181
|
+
return Object.fromEntries(keys.filter((k) => opts[k] !== undefined).map((k) => [k, opts[k]]));
|
|
182
|
+
}
|