Files

438 lines
14 KiB
JavaScript

import { main } from '../../bin/main.js';
import { htmlIsEqual } from '@markedjs/testutils';
import { resolve } from 'node:path';
import { describe, it, mock } from 'node:test';
import assert from 'node:assert';
import { exec, execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { mkdtemp, readFile, rm, symlink, writeFile, access } from 'node:fs/promises';
import { tmpdir } from 'node:os';
const execAsync = promisify(exec);
const execFileAsync = promisify(execFile);
function createMocks() {
const mocks = {
stdout: '',
stderr: '',
code: null,
stdin: {
data: null,
error: null,
end: null,
},
process: {
cwd: mock.fn(() => '/cwd'),
env: [],
argv: [],
stdout: {
write: mock.fn((str, callback) => {
mocks.stdout += str;
callback?.();
}),
},
stderr: {
write: mock.fn((str, callback) => {
mocks.stderr += str;
callback?.();
}),
},
stdin: {
setEncoding: mock.fn(),
on: mock.fn((method, func) => {
mocks.stdin[method] = func;
}),
resume: mock.fn(),
},
exit: mock.fn((code) => { mocks.code = code; }),
},
};
return mocks;
}
function testInput({ args = [], stdin = '', stdinError = '', stdout = '', stderr = '', code = 0 } = {}) {
return async() => {
const mocks = createMocks();
mocks.process.argv = ['node', 'marked', ...args];
const mainPromise = main(mocks.process);
if (typeof mocks.stdin.end === 'function') {
if (stdin) {
mocks.stdin.data(stdin);
}
if (stdinError) {
mocks.stdin.error(stdinError);
}
mocks.stdin.end();
}
await mainPromise;
assert.ok(await htmlIsEqual(mocks.stdout, stdout));
assert.strictEqual(mocks.stderr, stderr);
assert.strictEqual(mocks.code, code);
};
}
function fixturePath(filePath) {
return resolve(import.meta.dirname, './fixtures', filePath);
}
async function execMarkedString(args, markdown) {
const { stdout, stderr } = await execFileAsync(process.execPath, [
resolve(import.meta.dirname, '../../bin/marked.js'),
...args, '--string', markdown,
]);
assert.strictEqual(stderr, '');
return stdout;
}
function execMarked({ args = '', stdin = '', stdout = '', stderr = '' }) {
const execPath = resolve(import.meta.dirname, '../../bin/marked');
return async() => {
let command = '';
if (stdin) {
command += `node -e "process.stdout.write('${stdin}')" | `;
}
command += `node ${execPath}`;
if (args) {
command += ` ${args}`;
}
const res = await execAsync(command);
assert.ok(await htmlIsEqual(res.stdout, stdout));
assert.strictEqual(res.stderr, stderr);
};
}
describe('bin/marked', () => {
describe('required option values', () => {
for (const option of ['-o', '--output', '-i', '--input', '-s', '--string', '-c', '--config']) {
it(`rejects ${option} without a value`, testInput({
args: [option],
stdin: '# ignored',
stderr: `marked: option '${option}' requires an argument`,
code: 1,
}));
}
});
describe('output', () => {
it('writes all error output before exiting when stderr is piped', async() => {
const dir = await mkdtemp(resolve(tmpdir(), 'marked-stderr-'));
try {
const config = resolve(dir, 'config.cjs');
const message = 'config error '.repeat(131072);
await writeFile(config, `module.exports = () => { throw new Error(${JSON.stringify(message)}); };\n`);
await assert.rejects(execFileAsync(process.execPath, [
resolve(import.meta.dirname, '../../bin/marked.js'),
'--config', config, '--string', '# test',
], { maxBuffer: 4 * 1024 * 1024 }), (err) => {
assert.strictEqual(err.code, 1);
assert.strictEqual(err.stdout, '');
assert.strictEqual(err.stderr.length, message.length);
assert.strictEqual(err.stderr, message);
return true;
});
} finally {
await rm(dir, { recursive: true, force: true });
}
});
it('writes all output before exiting when stdout is piped', async() => {
const dir = await mkdtemp(resolve(tmpdir(), 'marked-stdout-'));
try {
const input = resolve(dir, 'input.md');
const markdown = 'markdown output '.repeat(131072);
await writeFile(input, markdown);
const { stdout, stderr } = await execFileAsync(process.execPath, [
resolve(import.meta.dirname, '../../bin/marked.js'),
'--input', input,
], { maxBuffer: 4 * 1024 * 1024 });
assert.strictEqual(stdout, `<p>${markdown}</p>\n\n`);
assert.strictEqual(stderr, '');
} finally {
await rm(dir, { recursive: true, force: true });
}
});
it('does not follow an existing dangling symlink with --no-clobber', { skip: process.platform === 'win32' }, async() => {
const dir = await mkdtemp(resolve(tmpdir(), 'marked-no-clobber-'));
try {
const output = resolve(dir, 'output.html');
const target = resolve(dir, 'target.html');
await symlink(target, output);
await testInput({
args: ['--no-clobber', '--output', output, '--string', '# test'],
stderr: `marked: output file '${output}' already exists, disable the '-n' / '--no-clobber' flag to overwrite\n`,
code: 1,
})();
await assert.rejects(access(target), { code: 'ENOENT' });
} finally {
await rm(dir, { recursive: true, force: true });
}
});
it('preserves an existing file with --no-clobber', async() => {
const dir = await mkdtemp(resolve(tmpdir(), 'marked-no-clobber-'));
try {
const output = resolve(dir, 'output.html');
await writeFile(output, 'original');
await testInput({
args: ['--no-clobber', '--output', output, '--string', '# test'],
stderr: `marked: output file '${output}' already exists, disable the '-n' / '--no-clobber' flag to overwrite\n`,
code: 1,
})();
assert.strictEqual(await readFile(output, 'utf8'), 'original');
} finally {
await rm(dir, { recursive: true, force: true });
}
});
for (const args of [[], ['--no-clobber']]) {
it(`creates a new output file with ${args.join(' ') || 'default options'}`, async() => {
const dir = await mkdtemp(resolve(tmpdir(), 'marked-no-clobber-'));
try {
const output = resolve(dir, 'output.html');
await testInput({ args: [...args, '--output', output, '--string', '# test'] })();
assert.strictEqual(await readFile(output, 'utf8'), '<h1>test</h1>\n');
} finally {
await rm(dir, { recursive: true, force: true });
}
});
}
it('overwrites an existing output file by default', async() => {
const dir = await mkdtemp(resolve(tmpdir(), 'marked-no-clobber-'));
try {
const output = resolve(dir, 'output.html');
await writeFile(output, 'original');
await testInput({ args: ['--output', output, '--string', '# test'] })();
assert.strictEqual(await readFile(output, 'utf8'), '<h1>test</h1>\n');
} finally {
await rm(dir, { recursive: true, force: true });
}
});
});
describe('string', () => {
it('--string= accepts empty input instead of reading stdin', testInput({
args: ['--string='],
stdin: '# ignored',
stdout: '\n',
}));
it('-s', testInput({
args: ['-s', '# test'],
stdout: '<h1>test</h1>',
}));
it('--string', testInput({
args: ['--string', '# test'],
stdout: '<h1>test</h1>',
}));
it('--string accepts empty input instead of reading stdin', testInput({
args: ['--string', ''],
stdin: '# ignored',
stdout: '\n',
}));
});
describe('config', () => {
it('uses GFM by default', async() => {
const result = await execMarkedString([], '~~test~~');
assert.strictEqual(result, '<p><del>test</del></p>\n\n');
});
it('uses options from the config file in a separate process', async() => {
const result = await execMarkedString(['--config', fixturePath('bin-config.js')], 'line1\nline2');
assert.strictEqual(result, '<p>line1<br>line2</p>\n\n');
});
it('uses a tokenizer from the config file', async() => {
const result = await execMarkedString(['--config', fixturePath('bin-config-tokenizer.js')], '`test`');
assert.strictEqual(result, '<p><code>TEST</code></p>\n\n');
});
it('lets command-line options override config options', async() => {
const result = await execMarkedString(['--config', fixturePath('bin-config.js'), '--no-breaks'], 'line1\nline2');
assert.strictEqual(result, '<p>line1\nline2</p>\n\n');
});
it('-c', testInput({
args: ['-c', fixturePath('bin-config.js'), '-s', 'line1\nline2'],
stdout: '<p>line1<br>line2</p>',
}));
it('--config', testInput({
args: ['--config', fixturePath('bin-config.js'), '-s', 'line1\nline2'],
stdout: '<p>line1<br>line2</p>',
}));
it('config path with hash', testInput({
args: ['--config', fixturePath('bin-config#hash.js'), '-s', 'line1\nline2'],
stdout: '<p>line1<br>line2</p>',
}));
it('config with top-level await', testInput({
args: ['--config', fixturePath('bin-config-await.mjs'), '-s', 'line1\nline2'],
stdout: '<p>line1<br>line2</p>',
}));
it('config with a synchronous function', testInput({
args: ['--config', fixturePath('bin-config-function.js'), '-s', 'line1\nline2'],
stdout: '<p>line1<br>line2</p>',
}));
it('waits for an async config function', async() => {
const { stdout, stderr } = await execFileAsync(process.execPath, [
resolve(import.meta.dirname, '../../bin/marked.js'),
'--config', fixturePath('bin-config-async.mjs'),
'--string', 'line1\nline2',
]);
assert.strictEqual(stdout, '<p>line1<br>line2</p>\n\n');
assert.strictEqual(stderr, '');
});
it('reports a rejected config function', async() => {
await assert.rejects(execFileAsync(process.execPath, [
resolve(import.meta.dirname, '../../bin/marked.js'),
'--config', fixturePath('bin-config-reject.cjs'),
'--string', '# test',
]), {
code: 1,
stdout: '',
stderr: 'Async config failed',
});
});
it('config not found', testInput({
args: ['--config', fixturePath('does-not-exist.js'), '-s', 'line1\nline2'],
stderr: `Cannot load config file '${fixturePath('does-not-exist.js')}'`,
code: 1,
}));
});
describe('tokens', () => {
async function tokens(args, markdown) {
const stdout = await execMarkedString(['--tokens', ...args], markdown);
return JSON.parse(stdout);
}
it('uses GFM by default', async() => {
const result = await tokens([], '~~test~~');
assert.strictEqual(result[0].tokens[0].type, 'del');
});
it('uses options from the config file', async() => {
const result = await tokens(['--config', fixturePath('bin-config.js')], 'line1\nline2');
assert.deepStrictEqual(result[0].tokens.map(token => token.type), ['text', 'br', 'text']);
});
it('uses a tokenizer from the config file', async() => {
const result = await tokens(['--config', fixturePath('bin-config-tokenizer.js')], '`test`');
assert.strictEqual(result[0].tokens[0].type, 'codespan');
assert.strictEqual(result[0].tokens[0].text, 'TEST');
});
it('lets command-line options override config options', async() => {
const result = await tokens(['--config', fixturePath('bin-config.js'), '--no-breaks'], 'line1\nline2');
assert.deepStrictEqual(result[0].tokens.map(token => token.type), ['text']);
});
});
describe('input', () => {
it('does not treat --=value as the end of options', testInput({
args: ['--=ignored', '--string', '# test'],
stdout: '<h1>test</h1>',
}));
it('does not treat the value of an unknown --option=value as an input file', testInput({
args: ['--unknown=ignored'],
stdin: '# test\n',
stdout: '<h1>test</h1>',
}));
it('supports --option=false for boolean options without treating false as a file', testInput({
args: ['--gfm=false'],
stdin: '~~text~~\n',
stdout: '<p>~~text~~</p>',
}));
it('ignores prototype property names like --to-string without consuming the next argument', testInput({
args: ['--to-string', fixturePath('bin-input.md')],
stdout: '<h1>file</h1>',
}));
for (const filename of ['-s.md', '--version']) {
it(`treats ${filename} as a filename after --`, async() => {
const dir = await mkdtemp(resolve(tmpdir(), 'marked-end-options-'));
try {
await writeFile(resolve(dir, filename), '~~file contents~~');
const { stdout, stderr } = await execFileAsync(process.execPath, [
resolve(import.meta.dirname, '../../bin/marked.js'),
'--no-gfm', '--', filename,
], { cwd: dir });
assert.strictEqual(stdout, '<p>~~file contents~~</p>\n\n');
assert.strictEqual(stderr, '');
} finally {
await rm(dir, { recursive: true, force: true });
}
});
}
it('input file positional', testInput({
args: [fixturePath('bin-input.md')],
stdout: '<h1>file</h1>',
}));
it('input file not found', testInput({
args: [fixturePath('does-not-exist.md')],
stderr: `marked: ${fixturePath('does-not-exist.md')}: No such file or directory`,
code: 1,
}));
it('input file not found --input', testInput({
args: ['--input', fixturePath('does-not-exist.md')],
stderr: `marked: ${fixturePath('does-not-exist.md')}: No such file or directory`,
code: 1,
}));
it('reads from stdin when no files are provided', testInput({
stdin: '# test\n',
stdout: '<h1>test</h1>',
}));
});
});
describe('exec', () => {
it('stdin', execMarked({
stdin: '# test',
stdout: '<h1>test</h1>',
}));
it('string', execMarked({
args: '-s "# test"',
stdout: '<h1>test</h1>',
}));
it('input', execMarked({
args: `-i ${fixturePath('bin-input.md')}`,
stdout: '<h1>file</h1>',
}));
it('input file positional', execMarked({
args: fixturePath('bin-input.md'),
stdout: '<h1>file</h1>',
}));
it('input last file positional', execMarked({
args: `${fixturePath('does-not-exist.md')} ${fixturePath('bin-input.md')}`,
stdout: '<h1>file</h1>',
}));
});