@rickycourtes/mdtest 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +296 -2
- package/bin/mdtest.js +12 -0
- package/package.json +53 -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/cli.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import { collect, run } from './run.js';
|
|
5
|
+
import { defaultReporter, formatList, toJSON } from './reporter.js';
|
|
6
|
+
|
|
7
|
+
const HELP = `mdtest — tests written in Markdown, checked by Claude
|
|
8
|
+
|
|
9
|
+
Usage
|
|
10
|
+
mdtest [pattern...] [options] Run the tests
|
|
11
|
+
mdtest init [--testDir dir] [--force]
|
|
12
|
+
Add a tests folder, config file and npm script
|
|
13
|
+
|
|
14
|
+
Patterns filter test file paths (regex), or name test files directly.
|
|
15
|
+
Test files: every .md in tests/ (except README.md and setup.md),
|
|
16
|
+
plus **/*.test.md and **/*.spec.md anywhere.
|
|
17
|
+
|
|
18
|
+
Options
|
|
19
|
+
-c, --config <path> Config file (default: mdtest.config.{js,mjs,json})
|
|
20
|
+
-t, --testNamePattern <re> Run only tests whose full name matches
|
|
21
|
+
--fix Let Claude change code until tests pass
|
|
22
|
+
--list List the tests without running them (free)
|
|
23
|
+
-b, --bail Stop after the first failing test
|
|
24
|
+
-j, --concurrency <n> Tests checked at once (default 4; fix mode: 1)
|
|
25
|
+
-m, --model <id> Claude model, e.g. claude-opus-5-5
|
|
26
|
+
-e, --effort <level> low | medium | high | xhigh | max
|
|
27
|
+
--timeout <ms> Per-test timeout (default 300000)
|
|
28
|
+
--maxBudgetUsd <usd> Per-test spending cap
|
|
29
|
+
--retries <n> Retry a test that ended without a verdict
|
|
30
|
+
--json Print results as JSON
|
|
31
|
+
--outputFile <path> Write JSON results to a file
|
|
32
|
+
--rootDir <dir> Project directory (default: cwd)
|
|
33
|
+
--testDir <dir> Test folder (default: tests)
|
|
34
|
+
--version Print the version
|
|
35
|
+
-v, --verbose Stream Claude's tool calls as it works
|
|
36
|
+
-h, --help Show this help
|
|
37
|
+
|
|
38
|
+
Exit code is 1 when any test fails.`;
|
|
39
|
+
|
|
40
|
+
/** @param {string[]} argv */
|
|
41
|
+
export async function main(argv) {
|
|
42
|
+
const { values, positionals } = parseArgs({
|
|
43
|
+
args: argv,
|
|
44
|
+
allowPositionals: true,
|
|
45
|
+
options: {
|
|
46
|
+
testNamePattern: { type: 'string', short: 't' },
|
|
47
|
+
fix: { type: 'boolean' },
|
|
48
|
+
list: { type: 'boolean' },
|
|
49
|
+
bail: { type: 'boolean', short: 'b' },
|
|
50
|
+
concurrency: { type: 'string', short: 'j' },
|
|
51
|
+
model: { type: 'string', short: 'm' },
|
|
52
|
+
effort: { type: 'string', short: 'e' },
|
|
53
|
+
timeout: { type: 'string' },
|
|
54
|
+
maxBudgetUsd: { type: 'string' },
|
|
55
|
+
retries: { type: 'string' },
|
|
56
|
+
json: { type: 'boolean' },
|
|
57
|
+
outputFile: { type: 'string' },
|
|
58
|
+
rootDir: { type: 'string' },
|
|
59
|
+
config: { type: 'string', short: 'c' },
|
|
60
|
+
testDir: { type: 'string' },
|
|
61
|
+
force: { type: 'boolean' },
|
|
62
|
+
verbose: { type: 'boolean', short: 'v' },
|
|
63
|
+
help: { type: 'boolean', short: 'h' },
|
|
64
|
+
version: { type: 'boolean' },
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
if (values.help) {
|
|
69
|
+
console.log(HELP);
|
|
70
|
+
return 0;
|
|
71
|
+
}
|
|
72
|
+
if (values.version) {
|
|
73
|
+
const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
|
|
74
|
+
console.log(pkg.version);
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const rootDir = resolve(values.rootDir ?? process.cwd());
|
|
79
|
+
if (positionals[0] === 'init') {
|
|
80
|
+
const { init } = await import('./init.js');
|
|
81
|
+
await init({ rootDir, testDir: values.testDir, force: values.force });
|
|
82
|
+
return 0;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const num = (v) => (v === undefined ? undefined : Number(v));
|
|
86
|
+
const options = {
|
|
87
|
+
rootDir,
|
|
88
|
+
configPath: values.config,
|
|
89
|
+
patterns: positionals,
|
|
90
|
+
testNamePattern: values.testNamePattern,
|
|
91
|
+
fix: values.fix,
|
|
92
|
+
bail: values.bail,
|
|
93
|
+
config: {
|
|
94
|
+
testDir: values.testDir,
|
|
95
|
+
model: values.model,
|
|
96
|
+
effort: values.effort,
|
|
97
|
+
concurrency: num(values.concurrency),
|
|
98
|
+
timeout: num(values.timeout),
|
|
99
|
+
maxBudgetUsd: num(values.maxBudgetUsd),
|
|
100
|
+
retries: num(values.retries),
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
if (values.list) {
|
|
105
|
+
const { files } = await collect(options);
|
|
106
|
+
console.log(values.json ? JSON.stringify(files, null, 2) : formatList(files));
|
|
107
|
+
return 0;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const summary = await run({
|
|
111
|
+
...options,
|
|
112
|
+
reporter: values.json ? {} : defaultReporter({ verbose: values.verbose }),
|
|
113
|
+
});
|
|
114
|
+
const json = toJSON(summary);
|
|
115
|
+
if (values.json) console.log(JSON.stringify(json, null, 2));
|
|
116
|
+
if (values.outputFile) await writeFile(values.outputFile, JSON.stringify(json, null, 2));
|
|
117
|
+
return summary.success ? 0 : 1;
|
|
118
|
+
}
|
package/src/discover.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
|
|
6
|
+
export const CONFIG_FILES = ['mdtest.config.js', 'mdtest.config.mjs', 'mdtest.config.json'];
|
|
7
|
+
|
|
8
|
+
export const DEFAULTS = {
|
|
9
|
+
/** Folder that holds the Markdown tests. Every .md file in it is a test file. */
|
|
10
|
+
testDir: 'tests',
|
|
11
|
+
/** Globs (relative to rootDir) that find test files. <testDir> is replaced. */
|
|
12
|
+
testMatch: ['<testDir>/**/*.md', '**/*.test.md', '**/*.spec.md'],
|
|
13
|
+
/** Regexes tested against "/" + the relative path. Matches are not test files. */
|
|
14
|
+
testPathIgnorePatterns: ['/node_modules/', '/\\.git/', '/README\\.md$'],
|
|
15
|
+
/** Markdown files added as context to every test, and never run as tests. */
|
|
16
|
+
setupFiles: ['<testDir>/setup.md'],
|
|
17
|
+
model: undefined,
|
|
18
|
+
effort: undefined,
|
|
19
|
+
concurrency: 4,
|
|
20
|
+
timeout: 300_000,
|
|
21
|
+
maxTurns: 40,
|
|
22
|
+
maxBudgetUsd: undefined,
|
|
23
|
+
tools: ['Read', 'Grep', 'Glob', 'Bash'],
|
|
24
|
+
retries: 0,
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @typedef {typeof DEFAULTS & { rootDir: string, configFile?: string, explicitSetupFiles: boolean }} Config
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Loads the config. Looks for, in order: the --config path, mdtest.config.js,
|
|
33
|
+
* mdtest.config.mjs, mdtest.config.json, then the "mdtest" key of package.json.
|
|
34
|
+
* rootDir defaults to the folder that holds the config file.
|
|
35
|
+
* @param {string} cwd
|
|
36
|
+
* @param {Partial<Config>} [overrides]
|
|
37
|
+
* @param {string} [configPath]
|
|
38
|
+
* @returns {Promise<Config>}
|
|
39
|
+
*/
|
|
40
|
+
export async function loadConfig(cwd, overrides = {}, configPath) {
|
|
41
|
+
let file;
|
|
42
|
+
if (configPath) {
|
|
43
|
+
file = resolve(cwd, configPath);
|
|
44
|
+
if (!existsSync(file)) throw new Error(`Config file not found: ${configPath}`);
|
|
45
|
+
} else {
|
|
46
|
+
file = CONFIG_FILES.map((f) => join(cwd, f)).find(existsSync);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** @type {Record<string, any>} */
|
|
50
|
+
let fromFile = {};
|
|
51
|
+
if (file) fromFile = await readConfigFile(file);
|
|
52
|
+
else if (existsSync(join(cwd, 'package.json'))) {
|
|
53
|
+
fromFile = { ...JSON.parse(await readFile(join(cwd, 'package.json'), 'utf8')).mdtest };
|
|
54
|
+
}
|
|
55
|
+
delete fromFile.$schema;
|
|
56
|
+
const unknown = Object.keys(fromFile).filter((k) => !(k in DEFAULTS) && k !== 'rootDir');
|
|
57
|
+
if (unknown.length) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
`Unknown option${unknown.length > 1 ? 's' : ''} in ${file ? relative(cwd, file) : 'package.json "mdtest"'}: ${unknown.join(', ')}\n` +
|
|
60
|
+
`Valid options: ${[...Object.keys(DEFAULTS), 'rootDir'].join(', ')}`,
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const base = file ? dirname(file) : cwd;
|
|
65
|
+
const defined = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined));
|
|
66
|
+
const merged = { ...DEFAULTS, ...fromFile, ...defined };
|
|
67
|
+
const rootDir = resolve(base, merged.rootDir ?? '.');
|
|
68
|
+
const testDir = String(merged.testDir).replace(/\/+$/, '') || '.';
|
|
69
|
+
const expand = (s) => s.replaceAll('<rootDir>/', '').replaceAll('<testDir>', testDir).replace(/^\.\//, '');
|
|
70
|
+
return {
|
|
71
|
+
...merged,
|
|
72
|
+
rootDir,
|
|
73
|
+
testDir,
|
|
74
|
+
testMatch: merged.testMatch.map(expand),
|
|
75
|
+
setupFiles: merged.setupFiles.map(expand),
|
|
76
|
+
explicitSetupFiles: 'setupFiles' in fromFile || 'setupFiles' in defined,
|
|
77
|
+
...(file ? { configFile: file } : {}),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** @param {string} file */
|
|
82
|
+
async function readConfigFile(file) {
|
|
83
|
+
if (file.endsWith('.json')) {
|
|
84
|
+
try {
|
|
85
|
+
return JSON.parse(await readFile(file, 'utf8'));
|
|
86
|
+
} catch (err) {
|
|
87
|
+
throw new Error(`Could not parse ${file}: ${err instanceof Error ? err.message : err}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const mod = await import(pathToFileURL(file).href);
|
|
91
|
+
const value = mod.default ?? mod;
|
|
92
|
+
return { ...(typeof value === 'function' ? await value() : value) };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Reads the setup files: Markdown context shared by every test.
|
|
97
|
+
* A missing default setup file is fine; a missing configured one is an error.
|
|
98
|
+
* @param {Config} config
|
|
99
|
+
* @returns {Promise<{ file: string, text: string }[]>}
|
|
100
|
+
*/
|
|
101
|
+
export async function readSetupFiles(config) {
|
|
102
|
+
const out = [];
|
|
103
|
+
for (const f of config.setupFiles) {
|
|
104
|
+
const abs = isAbsolute(f) ? f : join(config.rootDir, f);
|
|
105
|
+
if (!existsSync(abs)) {
|
|
106
|
+
if (config.explicitSetupFiles) throw new Error(`Setup file not found: ${f}`);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
const text = (await readFile(abs, 'utf8')).replace(/<!--[\s\S]*?-->/g, '').trim();
|
|
110
|
+
if (text) out.push({ file: toPosix(relative(config.rootDir, abs)), text });
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Finds test files under rootDir. Positional patterns filter paths like jest:
|
|
117
|
+
* each is a regex tested against the relative path, or an exact file path.
|
|
118
|
+
* @param {Config} config
|
|
119
|
+
* @param {string[]} [patterns]
|
|
120
|
+
* @returns {Promise<string[]>} paths relative to rootDir, sorted
|
|
121
|
+
*/
|
|
122
|
+
export async function findTestFiles(config, patterns = []) {
|
|
123
|
+
const root = config.rootDir;
|
|
124
|
+
const matchers = config.testMatch.map(globToRegExp);
|
|
125
|
+
const ignores = config.testPathIgnorePatterns.map((p) => new RegExp(p));
|
|
126
|
+
const setup = new Set(config.setupFiles.map((f) => toPosix(isAbsolute(f) ? relative(root, f) : f)));
|
|
127
|
+
const explicit = [];
|
|
128
|
+
const filters = [];
|
|
129
|
+
for (const p of patterns) {
|
|
130
|
+
const hit = [resolve(process.cwd(), p), resolve(root, p)].find((a) => existsSync(a));
|
|
131
|
+
if (hit && (await stat(hit)).isFile()) explicit.push(toPosix(relative(root, hit)));
|
|
132
|
+
else filters.push(new RegExp(p));
|
|
133
|
+
}
|
|
134
|
+
if (explicit.length && !filters.length) return [...new Set(explicit)].sort();
|
|
135
|
+
|
|
136
|
+
const found = [];
|
|
137
|
+
const walk = async (dir) => {
|
|
138
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
139
|
+
const abs = join(dir, entry.name);
|
|
140
|
+
const rel = toPosix(relative(root, abs));
|
|
141
|
+
if (ignores.some((r) => r.test(`/${rel}${entry.isDirectory() ? '/' : ''}`))) continue;
|
|
142
|
+
if (entry.isDirectory()) await walk(abs);
|
|
143
|
+
else if (entry.isFile() && !setup.has(rel) && matchers.some((m) => m.test(rel))) found.push(rel);
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
await walk(root);
|
|
147
|
+
const filtered = filters.length ? found.filter((f) => filters.some((r) => r.test(f))) : found;
|
|
148
|
+
return [...new Set([...filtered, ...explicit])].sort();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** @param {string} glob */
|
|
152
|
+
export function globToRegExp(glob) {
|
|
153
|
+
let re = '';
|
|
154
|
+
for (let i = 0; i < glob.length; i++) {
|
|
155
|
+
const c = glob[i];
|
|
156
|
+
if (c === '*' && glob[i + 1] === '*') {
|
|
157
|
+
if (glob[i + 2] === '/') {
|
|
158
|
+
re += '(?:.*/)?';
|
|
159
|
+
i += 2;
|
|
160
|
+
} else {
|
|
161
|
+
re += '.*';
|
|
162
|
+
i += 1;
|
|
163
|
+
}
|
|
164
|
+
} else if (c === '*') re += '[^/]*';
|
|
165
|
+
else if (c === '?') re += '[^/]';
|
|
166
|
+
else re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
167
|
+
}
|
|
168
|
+
return new RegExp(`^${re}$`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** @param {string} p */
|
|
172
|
+
const toPosix = (p) => p.split(sep).join('/');
|
package/src/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { parse } from './parse.js';
|
|
2
|
+
export { collect, run } from './run.js';
|
|
3
|
+
export { loadConfig, findTestFiles, readSetupFiles, globToRegExp, DEFAULTS, CONFIG_FILES } from './discover.js';
|
|
4
|
+
export { verifyWithClaude, buildPrompt } from './claude.js';
|
|
5
|
+
export { defaultReporter, formatList, toJSON } from './reporter.js';
|
|
6
|
+
export { init } from './init.js';
|
package/src/init.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// `mdtest init`: sets a project up with a tests folder, a config file and an
|
|
2
|
+
// npm script.
|
|
3
|
+
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { CONFIG_FILES } from './discover.js';
|
|
8
|
+
|
|
9
|
+
const PKG = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
|
|
10
|
+
|
|
11
|
+
const SETUP = `<!--
|
|
12
|
+
Context for every test in this project. Claude reads this before each test,
|
|
13
|
+
so say where things live and how to run them. Keep it short; this file is
|
|
14
|
+
never run as a test itself.
|
|
15
|
+
-->
|
|
16
|
+
|
|
17
|
+
# About this project
|
|
18
|
+
|
|
19
|
+
{{about}}
|
|
20
|
+
`;
|
|
21
|
+
|
|
22
|
+
const EXAMPLE_NODE = `# Project
|
|
23
|
+
|
|
24
|
+
Each heading with no sub-headings is one test. Write what should be true,
|
|
25
|
+
in plain language. Claude checks it against the code.
|
|
26
|
+
|
|
27
|
+
## has a package manifest
|
|
28
|
+
|
|
29
|
+
There is a \`package.json\` at the project root, and its \`name\` field is
|
|
30
|
+
\`{{name}}\`.
|
|
31
|
+
|
|
32
|
+
## todo: describe your first real behaviour
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
const EXAMPLE_GENERIC = `# Project
|
|
36
|
+
|
|
37
|
+
Each heading with no sub-headings is one test. Write what should be true,
|
|
38
|
+
in plain language. Claude checks it against the code.
|
|
39
|
+
|
|
40
|
+
## todo: describe your first real behaviour
|
|
41
|
+
`;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @param {{ rootDir: string, testDir?: string, force?: boolean, log?: (s: string) => void }} opts
|
|
45
|
+
* @returns {Promise<string[]>} the paths it wrote, relative to rootDir
|
|
46
|
+
*/
|
|
47
|
+
export async function init({ rootDir, testDir = 'tests', force = false, log = console.log }) {
|
|
48
|
+
const written = [];
|
|
49
|
+
const write = async (rel, content) => {
|
|
50
|
+
const abs = join(rootDir, rel);
|
|
51
|
+
if (existsSync(abs) && !force) {
|
|
52
|
+
log(` skip ${rel} (exists)`);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
await mkdir(join(abs, '..'), { recursive: true });
|
|
56
|
+
await writeFile(abs, content);
|
|
57
|
+
written.push(rel);
|
|
58
|
+
log(` create ${rel}`);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const pkgPath = join(rootDir, 'package.json');
|
|
62
|
+
const pkg = existsSync(pkgPath) ? JSON.parse(await readFile(pkgPath, 'utf8')) : null;
|
|
63
|
+
|
|
64
|
+
const existingConfig = CONFIG_FILES.find((f) => existsSync(join(rootDir, f)));
|
|
65
|
+
if (existingConfig && !force) log(` skip ${existingConfig} (exists)`);
|
|
66
|
+
else {
|
|
67
|
+
const config = {
|
|
68
|
+
$schema: `./node_modules/${PKG.name}/schema.json`,
|
|
69
|
+
testDir,
|
|
70
|
+
setupFiles: [`${testDir}/setup.md`],
|
|
71
|
+
concurrency: 4,
|
|
72
|
+
timeout: 300000,
|
|
73
|
+
};
|
|
74
|
+
await write('mdtest.config.json', `${JSON.stringify(config, null, 2)}\n`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const about = pkg?.description
|
|
78
|
+
? `${pkg.description}`
|
|
79
|
+
: 'Describe the project in a sentence or two: what it is and where its code lives.';
|
|
80
|
+
await write(`${testDir}/setup.md`, SETUP.replace('{{about}}', about));
|
|
81
|
+
await write(
|
|
82
|
+
`${testDir}/example.md`,
|
|
83
|
+
pkg?.name ? EXAMPLE_NODE.replace('{{name}}', pkg.name) : EXAMPLE_GENERIC,
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
if (pkg) {
|
|
87
|
+
pkg.scripts ??= {};
|
|
88
|
+
// npm init's placeholder test script counts as no test script.
|
|
89
|
+
const placeholder = /no test specified/.test(String(pkg.scripts.test ?? ''));
|
|
90
|
+
const name = pkg.scripts.test && !placeholder ? 'test:md' : 'test';
|
|
91
|
+
if (Object.values(pkg.scripts).some((s) => /\bmdtest\b/.test(String(s)))) {
|
|
92
|
+
log(' skip package.json script (already runs mdtest)');
|
|
93
|
+
} else {
|
|
94
|
+
pkg.scripts[name] = 'mdtest';
|
|
95
|
+
const raw = await readFile(pkgPath, 'utf8');
|
|
96
|
+
const indent = /^(\s+)"/m.exec(raw)?.[1] ?? ' ';
|
|
97
|
+
await writeFile(pkgPath, `${JSON.stringify(pkg, null, indent)}\n`);
|
|
98
|
+
written.push('package.json');
|
|
99
|
+
log(` update package.json (scripts.${name} = "mdtest")`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
log('');
|
|
104
|
+
log('Next:');
|
|
105
|
+
log(` 1. Describe your project in ${testDir}/setup.md`);
|
|
106
|
+
log(` 2. Write tests as Markdown files in ${testDir}/`);
|
|
107
|
+
log(' 3. npx mdtest --list (free: shows the tests it found)');
|
|
108
|
+
log(' 4. npx mdtest (needs ANTHROPIC_API_KEY or a Claude Code login)');
|
|
109
|
+
return written;
|
|
110
|
+
}
|
package/src/parse.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Turns a Markdown test file into a tree of suites and tests.
|
|
2
|
+
//
|
|
3
|
+
// Text before the first heading context for every test in the file
|
|
4
|
+
// A heading with sub-headings a suite (describe); its text is context
|
|
5
|
+
// A heading with no sub-headings a test (it); its text is the test
|
|
6
|
+
// "skip:", "only:", "todo:" heading prefixes, like it.skip / it.only / it.todo
|
|
7
|
+
// A test with no text todo
|
|
8
|
+
// <!-- comments --> stripped; never sent to Claude
|
|
9
|
+
|
|
10
|
+
const MODES = ['skip', 'only', 'todo'];
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @typedef {'run' | 'skip' | 'only' | 'todo'} Mode
|
|
14
|
+
* @typedef {{
|
|
15
|
+
* id: string, file: string, line: number, name: string, path: string[],
|
|
16
|
+
* fullName: string, body: string, context: string[], mode: Mode,
|
|
17
|
+
* }} TestCase
|
|
18
|
+
* @typedef {{ file: string, options: Record<string, unknown>, tests: TestCase[] }} TestFile
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {string} source
|
|
23
|
+
* @param {string} [file]
|
|
24
|
+
* @returns {TestFile}
|
|
25
|
+
*/
|
|
26
|
+
export function parse(source, file = '<inline>') {
|
|
27
|
+
const { options, body, offset } = frontmatter(source.replace(/\r\n?/g, '\n'));
|
|
28
|
+
const lines = stripComments(body).split('\n');
|
|
29
|
+
|
|
30
|
+
/** @type {{ level: number, title: string, line: number, text: string[], children: any[] }} */
|
|
31
|
+
const root = { level: 0, title: '', line: 0, text: [], children: [] };
|
|
32
|
+
const stack = [root];
|
|
33
|
+
let fence = null;
|
|
34
|
+
|
|
35
|
+
lines.forEach((raw, i) => {
|
|
36
|
+
const fenceMatch = /^\s{0,3}(`{3,}|~{3,})/.exec(raw);
|
|
37
|
+
if (fenceMatch) {
|
|
38
|
+
const marker = fenceMatch[1];
|
|
39
|
+
if (!fence) fence = marker;
|
|
40
|
+
else if (marker[0] === fence[0] && marker.length >= fence.length) fence = null;
|
|
41
|
+
}
|
|
42
|
+
const heading = fence || fenceMatch ? null : /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(raw);
|
|
43
|
+
if (!heading) {
|
|
44
|
+
stack[stack.length - 1].text.push(raw);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const level = heading[1].length;
|
|
48
|
+
while (stack[stack.length - 1].level >= level) stack.pop();
|
|
49
|
+
const node = { level, title: heading[2], line: i + 1 + offset, text: [], children: [] };
|
|
50
|
+
stack[stack.length - 1].children.push(node);
|
|
51
|
+
stack.push(node);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
/** @type {TestCase[]} */
|
|
55
|
+
const tests = [];
|
|
56
|
+
const walk = (node, path, context, inherited) => {
|
|
57
|
+
const { mode, title } = splitMode(node.title);
|
|
58
|
+
const nodeMode = mode ?? inherited;
|
|
59
|
+
const text = clean(node.text);
|
|
60
|
+
if (node.children.length === 0) {
|
|
61
|
+
// A file with no headings is one test, named after the file.
|
|
62
|
+
if (node === root && !text) return;
|
|
63
|
+
const name = node === root ? fileTitle(file) : title;
|
|
64
|
+
const fullPath = [...path, name];
|
|
65
|
+
tests.push({
|
|
66
|
+
id: `${file}#${fullPath.join(' › ')}`,
|
|
67
|
+
file,
|
|
68
|
+
line: node.line,
|
|
69
|
+
name,
|
|
70
|
+
path,
|
|
71
|
+
fullName: fullPath.join(' › '),
|
|
72
|
+
body: text,
|
|
73
|
+
context,
|
|
74
|
+
mode: text ? nodeMode : nodeMode === 'skip' ? 'skip' : 'todo',
|
|
75
|
+
});
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const nextPath = node === root ? path : [...path, title];
|
|
79
|
+
const nextContext = text ? [...context, text] : context;
|
|
80
|
+
for (const child of node.children) walk(child, nextPath, nextContext, nodeMode);
|
|
81
|
+
};
|
|
82
|
+
walk(root, [], [], 'run');
|
|
83
|
+
|
|
84
|
+
// Like jest: if any test in the file is `only`, the rest are skipped.
|
|
85
|
+
if (tests.some((t) => t.mode === 'only')) {
|
|
86
|
+
for (const t of tests) if (t.mode === 'run') t.mode = 'skip';
|
|
87
|
+
}
|
|
88
|
+
return { file, options, tests };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** @param {string} title */
|
|
92
|
+
function splitMode(title) {
|
|
93
|
+
const m = /^(skip|only|todo)\s*:\s*(.*)$/i.exec(title);
|
|
94
|
+
if (!m) return { mode: null, title };
|
|
95
|
+
const mode = /** @type {Mode} */ (m[1].toLowerCase());
|
|
96
|
+
return { mode: MODES.includes(mode) ? mode : null, title: m[2] };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** @param {string} file */
|
|
100
|
+
function fileTitle(file) {
|
|
101
|
+
const base = file.split(/[\\/]/).pop() ?? file;
|
|
102
|
+
return base.replace(/\.(test|spec)\.md$|\.md$/i, '');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** @param {string[]} lines */
|
|
106
|
+
function clean(lines) {
|
|
107
|
+
return lines.join('\n').replace(/^\s*\n/, '').trimEnd();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Remove HTML comments, keeping line count so line numbers stay right. */
|
|
111
|
+
function stripComments(text) {
|
|
112
|
+
return text.replace(/<!--[\s\S]*?-->/g, (c) => '\n'.repeat(c.split('\n').length - 1));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* A small YAML subset: `key: value`, `key: [a, b]`, numbers and booleans.
|
|
117
|
+
* @param {string} source
|
|
118
|
+
*/
|
|
119
|
+
function frontmatter(source) {
|
|
120
|
+
const m = /^---\n([\s\S]*?)\n---\n?/.exec(source);
|
|
121
|
+
if (!m) return { options: {}, body: source, offset: 0 };
|
|
122
|
+
/** @type {Record<string, unknown>} */
|
|
123
|
+
const options = {};
|
|
124
|
+
for (const line of m[1].split('\n')) {
|
|
125
|
+
const kv = /^\s*([\w-]+)\s*:\s*(.*?)\s*$/.exec(line);
|
|
126
|
+
if (kv) options[kv[1]] = scalar(kv[2]);
|
|
127
|
+
}
|
|
128
|
+
return { options, body: source.slice(m[0].length), offset: m[0].split('\n').length - 1 };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** @param {string} v @returns {unknown} */
|
|
132
|
+
function scalar(v) {
|
|
133
|
+
if (/^\[.*\]$/.test(v)) return v.slice(1, -1).split(',').map((s) => scalar(s.trim())).filter((s) => s !== '');
|
|
134
|
+
if (/^(true|false)$/.test(v)) return v === 'true';
|
|
135
|
+
if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v);
|
|
136
|
+
return v.replace(/^(['"])(.*)\1$/, '$2');
|
|
137
|
+
}
|