stock-bot/libs/research/test/notebook-snapshot.test.ts

851 lines
29 KiB
TypeScript

import { createHash } from 'node:crypto';
import { describe, expect, test } from 'bun:test';
import { exportNotebookSnapshot as barrelExportNotebookSnapshot } from '../src/index';
import {
DEFAULT_MARIMO_COMMAND,
DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS,
exportNotebookSnapshot,
NotebookSnapshotError,
type NotebookCommandResult,
type NotebookCommandRunner,
type NotebookCommandRunOptions,
type NotebookSnapshotFileStat,
type NotebookSnapshotFs,
} from '../src/notebook-snapshot';
interface RecordedCall {
readonly command: string;
readonly args: readonly string[];
readonly options: NotebookCommandRunOptions;
}
interface FakeFsEntry {
readonly isFile: boolean;
bytes: Uint8Array;
}
class InMemoryNotebookFs implements NotebookSnapshotFs {
readonly entries = new Map<string, FakeFsEntry>();
readonly createdTempPaths: string[] = [];
readonly removedPaths: string[] = [];
readonly renames: Array<{ readonly from: string; readonly to: string }> = [];
failRenameError: Error | null = null;
failRemoveError: Error | null = null;
putFile(path: string, content: string | Uint8Array): void {
const bytes =
typeof content === 'string' ? new TextEncoder().encode(content) : new Uint8Array(content);
this.entries.set(path, { isFile: true, bytes });
}
putDirectory(path: string): void {
this.entries.set(path, { isFile: false, bytes: new Uint8Array(0) });
}
getBytes(path: string): Uint8Array | undefined {
const entry = this.entries.get(path);
return entry?.isFile ? entry.bytes : undefined;
}
getText(path: string): string | undefined {
const bytes = this.getBytes(path);
return bytes ? new TextDecoder().decode(bytes) : undefined;
}
async stat(path: string): Promise<NotebookSnapshotFileStat | null> {
const entry = this.entries.get(path);
if (!entry) {
return null;
}
return { isFile: entry.isFile, size: entry.bytes.byteLength };
}
async createExclusive(path: string): Promise<void> {
if (this.entries.has(path)) {
const err = new Error(`EEXIST: file already exists '${path}'`) as Error & { code: string };
err.code = 'EEXIST';
throw err;
}
this.entries.set(path, { isFile: true, bytes: new Uint8Array(0) });
this.createdTempPaths.push(path);
}
async readBytes(path: string): Promise<Uint8Array> {
const entry = this.entries.get(path);
if (!entry || !entry.isFile) {
const err = new Error(`ENOENT: no such file '${path}'`) as Error & { code: string };
err.code = 'ENOENT';
throw err;
}
return new Uint8Array(entry.bytes);
}
async rename(sourcePath: string, destinationPath: string): Promise<void> {
if (this.failRenameError) {
throw this.failRenameError;
}
const entry = this.entries.get(sourcePath);
if (!entry) {
const err = new Error(`ENOENT: no such file '${sourcePath}'`) as Error & { code: string };
err.code = 'ENOENT';
throw err;
}
this.entries.delete(sourcePath);
this.entries.set(destinationPath, entry);
this.renames.push({ from: sourcePath, to: destinationPath });
}
async remove(path: string): Promise<void> {
this.removedPaths.push(path);
if (this.failRemoveError) {
throw this.failRemoveError;
}
this.entries.delete(path);
}
}
type RunnerHandler = (
command: string,
args: readonly string[],
options: NotebookCommandRunOptions,
callIndex: number
) => Promise<NotebookCommandResult>;
function createRecordingRunner(handler: RunnerHandler): {
readonly runner: NotebookCommandRunner;
readonly calls: RecordedCall[];
} {
const calls: RecordedCall[] = [];
const runner: NotebookCommandRunner = {
async run(command, args, options) {
const callIndex = calls.length;
calls.push({ command, args: [...args], options: { ...options } });
return handler(command, args, options, callIndex);
},
};
return { runner, calls };
}
function makeTimeoutError(message = 'Command timed out'): Error & { code: string } {
const err = new Error(message) as Error & { code: string };
err.code = 'ETIMEDOUT';
return err;
}
async function expectSnapshotError(
promise: Promise<unknown>,
expectedCode: NotebookSnapshotError['code']
): Promise<NotebookSnapshotError> {
try {
await promise;
} catch (err) {
expect(err).toBeInstanceOf(NotebookSnapshotError);
const snapshotErr = err as NotebookSnapshotError;
expect(snapshotErr.code).toBe(expectedCode);
return snapshotErr;
}
throw new Error(`Expected NotebookSnapshotError(${expectedCode}), but promise resolved.`);
}
describe('exportNotebookSnapshot', () => {
test('is re-exported from the @stock-bot/research barrel', () => {
expect(barrelExportNotebookSnapshot).toBe(exportNotebookSnapshot);
});
test('happy path: runs check then export html with exact argv, publishes via sibling temp rename, and returns frozen receipt with exact non-ASCII bytes and sha256', async () => {
const fs = new InMemoryNotebookFs();
const notebookPath = '/workspace/research/notebooks/study.py';
const outputPath = '/workspace/artifacts/study.html';
fs.putFile(notebookPath, 'import marimo\n');
const nonAsciiHtml =
'<!doctype html><html><body><h1>CA Shorts — €100 / 日本語</h1></body></html>';
const expectedBytes = new TextEncoder().encode(nonAsciiHtml);
const expectedSha256 = createHash('sha256').update(expectedBytes).digest('hex');
const cleanReport = {
issues: [],
summary: { errored: false, total_files: 1 },
};
const { runner, calls } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: JSON.stringify(cleanReport), stderr: '' };
}
const outFlagIdx = args.indexOf('-o');
const tempPath = args[outFlagIdx + 1] as string;
fs.putFile(tempPath, expectedBytes);
return { exitCode: 0, stdout: '', stderr: '' };
});
const receipt = await exportNotebookSnapshot({
notebookPath,
outputPath,
runner,
fs,
allowedNotebookRoot: '/workspace/research/notebooks',
allowedOutputRoot: '/workspace/artifacts',
});
expect(calls).toHaveLength(2);
expect(calls[0]).toEqual({
command: DEFAULT_MARIMO_COMMAND,
args: ['check', '--format=json', notebookPath],
options: { timeoutMs: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS },
});
expect(fs.createdTempPaths).toHaveLength(1);
const tempPath = fs.createdTempPaths[0] as string;
expect(tempPath.startsWith('/workspace/artifacts/')).toBe(true);
expect(tempPath.endsWith('.html')).toBe(true);
expect(tempPath).not.toBe(outputPath);
expect(calls[1]).toEqual({
command: DEFAULT_MARIMO_COMMAND,
args: ['export', 'html', notebookPath, '-o', tempPath, '--force'],
options: { timeoutMs: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS },
});
expect(fs.renames).toEqual([{ from: tempPath, to: outputPath }]);
expect(fs.getBytes(tempPath)).toBeUndefined();
expect(fs.getBytes(outputPath)).toEqual(expectedBytes);
expect(Object.isFrozen(receipt)).toBe(true);
expect(Object.isFrozen(receipt.checkDiagnostics)).toBe(true);
expect(receipt).toEqual({
notebookPath,
outputPath,
bytes: expectedBytes.byteLength,
sha256: expectedSha256,
checkDiagnostics: cleanReport,
});
});
test('passes custom marimoCommand, timeoutMs, cwd, and notebook paths with spaces and shell metacharacters as single unmodified argv elements', async () => {
const fs = new InMemoryNotebookFs();
const trickyNotebook = "/work/my notebooks/study $(rm -rf) & 'quote'; echo hi | cat.py";
const outputPath = '/work/out/report snapshot.html';
fs.putFile(trickyNotebook, 'import marimo\n');
const { runner, calls } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: '', stderr: '' };
}
const tempPath = args[args.indexOf('-o') + 1] as string;
fs.putFile(tempPath, '<html>ok</html>');
return { exitCode: 0, stdout: '', stderr: '' };
});
const receipt = await exportNotebookSnapshot({
notebookPath: trickyNotebook,
outputPath,
runner,
fs,
marimoCommand: '/opt/uv/bin/marimo',
timeoutMs: 45_000,
cwd: '/work',
});
expect(calls).toHaveLength(2);
expect(calls[0]?.command).toBe('/opt/uv/bin/marimo');
expect(calls[0]?.args).toEqual(['check', '--format=json', trickyNotebook]);
expect(calls[0]?.options).toEqual({ cwd: '/work', timeoutMs: 45_000 });
expect(calls[1]?.command).toBe('/opt/uv/bin/marimo');
expect(calls[1]?.args[2]).toBe(trickyNotebook);
expect(calls[1]?.options).toEqual({ cwd: '/work', timeoutMs: 45_000 });
expect(receipt.checkDiagnostics).toBeNull();
});
test('accepts formatting and runtime advisories on clean exit 0', async () => {
const fs = new InMemoryNotebookFs();
const notebookPath = '/work/nb.py';
const outputPath = '/work/out.html';
fs.putFile(notebookPath, 'import marimo\n');
const advisoryReport = {
issues: [
{ code: 'MF001', severity: 'formatting', message: 'Formatting suggestion' },
{ code: 'MR001', severity: 'runtime', message: 'Runtime advisory' },
],
summary: { errored: false, total_files: 1 },
};
const { runner, calls } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: JSON.stringify(advisoryReport), stderr: '' };
}
const tempPath = args[args.indexOf('-o') + 1] as string;
fs.putFile(tempPath, '<html>advisory ok</html>');
return { exitCode: 0, stdout: '', stderr: '' };
});
const receipt = await exportNotebookSnapshot({ notebookPath, outputPath, runner, fs });
expect(calls).toHaveLength(2);
expect(receipt.checkDiagnostics).toEqual(advisoryReport);
expect(Object.isFrozen(receipt.checkDiagnostics?.issues)).toBe(true);
});
test('never invokes export when marimo check exits non-zero and preserves parsed diagnostics', async () => {
const fs = new InMemoryNotebookFs();
const notebookPath = '/work/bad.py';
const outputPath = '/work/out.html';
fs.putFile(notebookPath, 'def broken(:\n');
const failureReport = {
issues: [{ code: 'MB001', severity: 'breaking', message: 'Syntax error' }],
summary: { errored: true, total_files: 1 },
};
const { runner, calls } = createRecordingRunner(async () => ({
exitCode: 1,
stdout: JSON.stringify(failureReport),
stderr: 'check failed',
}));
const err = await expectSnapshotError(
exportNotebookSnapshot({ notebookPath, outputPath, runner, fs }),
'CHECK_FAILED'
);
expect(calls).toHaveLength(1);
expect(calls[0]?.args[0]).toBe('check');
expect(fs.createdTempPaths).toHaveLength(0);
expect((err.details as { diagnostics?: unknown }).diagnostics).toEqual(failureReport);
});
test('nonzero check exit takes precedence as CHECK_FAILED even when stdout is non-JSON', async () => {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/bad.py', 'import marimo\n');
const { runner, calls } = createRecordingRunner(async () => ({
exitCode: 2,
stdout: 'not json at all',
stderr: 'fatal error',
}));
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/bad.py',
outputPath: '/work/out.html',
runner,
fs,
}),
'CHECK_FAILED'
);
expect(calls).toHaveLength(1);
});
test('never invokes export when check exits 0 with whitespace-only stdout', async () => {
for (const stdout of ['\n', ' \t\r\n']) {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
fs.putFile('/work/out.html', '<html>existing-snapshot</html>');
const { runner, calls } = createRecordingRunner(async () => ({
exitCode: 0,
stdout,
stderr: '',
}));
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
}),
'CHECK_OUTPUT_INVALID'
);
expect(calls).toHaveLength(1);
expect(calls[0]?.args[0]).toBe('check');
expect(fs.createdTempPaths).toHaveLength(0);
expect(fs.getText('/work/out.html')).toBe('<html>existing-snapshot</html>');
}
});
test('never invokes export when check exits 0 with malformed JSON or invalid report shape', async () => {
const badOutputs = [
'{not-valid-json',
'[]',
'{}',
JSON.stringify({ issues: 'not-an-array', summary: { errored: false, total_files: 1 } }),
JSON.stringify({ issues: [], summary: { errored: 'false', total_files: 1 } }),
JSON.stringify({ issues: [], summary: { errored: false, total_files: 0 } }),
JSON.stringify({ issues: [], summary: { errored: false, total_files: 2 } }),
JSON.stringify({ issues: [123], summary: { errored: false, total_files: 1 } }),
];
for (const stdout of badOutputs) {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
const { runner, calls } = createRecordingRunner(async () => ({
exitCode: 0,
stdout,
stderr: '',
}));
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
}),
'CHECK_OUTPUT_INVALID'
);
expect(calls).toHaveLength(1);
expect(fs.createdTempPaths).toHaveLength(0);
}
});
test('never invokes export when check exits 0 with summary.errored, file error, or breaking diagnostic', async () => {
const blockingReports = [
{ issues: [], summary: { errored: true, total_files: 1 } },
{
issues: [{ type: 'error', message: 'Failed to parse notebook' }],
summary: { errored: false, total_files: 1 },
},
{
issues: [{ code: 'MB002', severity: 'breaking', message: 'Cycle detected' }],
summary: { errored: false, total_files: 1 },
},
{
issues: [
{
file: '/work/nb.py',
diagnostics: [{ code: 'MB003', severity: 'breaking', message: 'Multiple definitions' }],
},
],
summary: { errored: false, total_files: 1 },
},
];
for (const report of blockingReports) {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
const { runner, calls } = createRecordingRunner(async () => ({
exitCode: 0,
stdout: JSON.stringify(report),
stderr: '',
}));
const err = await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
}),
'CHECK_FAILED'
);
expect(calls).toHaveLength(1);
expect(fs.createdTempPaths).toHaveLength(0);
expect((err.details as { diagnostics?: unknown }).diagnostics).toEqual(report);
}
});
test('maps check timeout to TIMEOUT and never invokes export', async () => {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
fs.putFile('/work/out.html', '<html>original</html>');
const { runner, calls } = createRecordingRunner(async () => {
throw makeTimeoutError('check timed out');
});
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
timeoutMs: 5_000,
}),
'TIMEOUT'
);
expect(calls).toHaveLength(1);
expect(fs.createdTempPaths).toHaveLength(0);
expect(fs.getText('/work/out.html')).toBe('<html>original</html>');
});
test('fail-closed export: nonzero exit after partial HTML write removes temp and preserves existing destination', async () => {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
fs.putFile('/work/out.html', '<html>original-good-snapshot</html>');
const { runner } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: '', stderr: '' };
}
const tempPath = args[args.indexOf('-o') + 1] as string;
fs.putFile(tempPath, '<html>partial-broken-cell-output</html>');
return { exitCode: 1, stdout: '', stderr: 'ZeroDivisionError in cell 3' };
});
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
}),
'EXPORT_FAILED'
);
expect(fs.createdTempPaths).toHaveLength(1);
const tempPath = fs.createdTempPaths[0] as string;
expect(fs.removedPaths).toContain(tempPath);
expect(fs.getBytes(tempPath)).toBeUndefined();
expect(fs.getText('/work/out.html')).toBe('<html>original-good-snapshot</html>');
});
test('fail-closed export: missing or zero-byte temp output throws EXPORT_EMPTY, cleans temp, and preserves destination', async () => {
for (const mode of ['zero-byte', 'missing'] as const) {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
fs.putFile('/work/out.html', '<html>keep-me</html>');
const { runner } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: '', stderr: '' };
}
const tempPath = args[args.indexOf('-o') + 1] as string;
if (mode === 'missing') {
fs.entries.delete(tempPath);
}
// In 'zero-byte' mode, tempPath stays at 0 bytes from createExclusive.
return { exitCode: 0, stdout: '', stderr: '' };
});
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
}),
'EXPORT_EMPTY'
);
const tempPath = fs.createdTempPaths[0] as string;
expect(fs.removedPaths).toContain(tempPath);
expect(fs.getBytes(tempPath)).toBeUndefined();
expect(fs.getText('/work/out.html')).toBe('<html>keep-me</html>');
}
});
test('fail-closed export: export timeout after partial write throws TIMEOUT, removes temp, and preserves destination', async () => {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
fs.putFile('/work/out.html', '<html>keep-original</html>');
const { runner } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: '', stderr: '' };
}
const tempPath = args[args.indexOf('-o') + 1] as string;
fs.putFile(tempPath, '<html>partial-before-timeout</html>');
throw makeTimeoutError('export timed out');
});
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
timeoutMs: 1_000,
}),
'TIMEOUT'
);
const tempPath = fs.createdTempPaths[0] as string;
expect(fs.removedPaths).toContain(tempPath);
expect(fs.getBytes(tempPath)).toBeUndefined();
expect(fs.getText('/work/out.html')).toBe('<html>keep-original</html>');
});
test('fail-closed export: rename failure throws EXPORT_FAILED, removes temp, and preserves destination', async () => {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
fs.putFile('/work/out.html', '<html>prior-snapshot</html>');
fs.failRenameError = new Error('EXDEV: cross-device link not permitted');
const { runner } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: '', stderr: '' };
}
const tempPath = args[args.indexOf('-o') + 1] as string;
fs.putFile(tempPath, '<html>new-snapshot</html>');
return { exitCode: 0, stdout: '', stderr: '' };
});
const err = await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
}),
'EXPORT_FAILED'
);
const tempPath = fs.createdTempPaths[0] as string;
expect(err.cause).toBe(fs.failRenameError);
expect(fs.removedPaths).toContain(tempPath);
expect(fs.getBytes(tempPath)).toBeUndefined();
expect(fs.getText('/work/out.html')).toBe('<html>prior-snapshot</html>');
});
test('fail-closed export: rename failure preserves primary error if temp cleanup also fails', async () => {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
fs.putFile('/work/out.html', '<html>prior-snapshot</html>');
fs.failRenameError = new Error('EXDEV: cross-device link not permitted');
fs.failRemoveError = new Error('EIO: cleanup failed');
const { runner } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: '', stderr: '' };
}
const tempPath = args[args.indexOf('-o') + 1] as string;
fs.putFile(tempPath, '<html>new-snapshot</html>');
return { exitCode: 0, stdout: '', stderr: '' };
});
const err = await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
}),
'EXPORT_FAILED'
);
expect(err.cause).toBe(fs.failRenameError);
expect(fs.removedPaths).toContain(fs.createdTempPaths[0] as string);
expect(fs.getText('/work/out.html')).toBe('<html>prior-snapshot</html>');
});
test('uses a short sibling temp filename even when output basename is near POSIX NAME_MAX', async () => {
const fs = new InMemoryNotebookFs();
const notebookPath = '/work/nb.py';
const longBasename = `${'a'.repeat(250)}.html`;
const outputPath = `/work/${longBasename}`;
fs.putFile(notebookPath, 'import marimo\n');
const { runner } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: '', stderr: '' };
}
const tempPath = args[args.indexOf('-o') + 1] as string;
fs.putFile(tempPath, '<html>long-name-ok</html>');
return { exitCode: 0, stdout: '', stderr: '' };
});
await exportNotebookSnapshot({ notebookPath, outputPath, runner, fs });
expect(fs.createdTempPaths).toHaveLength(1);
const tempPath = fs.createdTempPaths[0] as string;
const tempBasename = tempPath.slice(tempPath.lastIndexOf('/') + 1);
expect(tempPath.startsWith('/work/')).toBe(true);
expect(tempBasename.endsWith('.html')).toBe(true);
expect(tempBasename.length).toBeLessThan(128);
expect(fs.getText(outputPath)).toBe('<html>long-name-ok</html>');
});
test('overlapping exports to the same outputPath reserve separate temp files without partial publication', async () => {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
fs.putFile('/work/out.html', '<html>initial</html>');
let releaseFirstExport: (() => void) | null = null;
const firstExportStarted = new Promise<void>(resolve => {
releaseFirstExport = resolve;
});
let unblockFirstExport: (() => void) | null = null;
const gateFirstExport = new Promise<void>(resolve => {
unblockFirstExport = resolve;
});
let exportCount = 0;
const { runner } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: '', stderr: '' };
}
exportCount += 1;
const myExport = exportCount;
const tempPath = args[args.indexOf('-o') + 1] as string;
if (myExport === 1) {
fs.putFile(tempPath, '<html>snapshot-A</html>');
releaseFirstExport?.();
await gateFirstExport;
return { exitCode: 0, stdout: '', stderr: '' };
}
fs.putFile(tempPath, '<html>snapshot-B</html>');
return { exitCode: 0, stdout: '', stderr: '' };
});
const firstPromise = exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
});
await firstExportStarted;
const secondReceipt = await exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
});
expect(fs.getText('/work/out.html')).toBe('<html>snapshot-B</html>');
unblockFirstExport?.();
const firstReceipt = await firstPromise;
expect(fs.createdTempPaths).toHaveLength(2);
expect(fs.createdTempPaths[0]).not.toBe(fs.createdTempPaths[1]);
expect(firstReceipt.bytes).toBe(new TextEncoder().encode('<html>snapshot-A</html>').byteLength);
expect(secondReceipt.bytes).toBe(
new TextEncoder().encode('<html>snapshot-B</html>').byteLength
);
expect(fs.getText('/work/out.html')).toBe('<html>snapshot-A</html>');
});
test('rejects invalid paths before any runner call', async () => {
const cases: Array<{
readonly name: string;
readonly notebookPath: string;
readonly outputPath: string;
readonly allowedNotebookRoot?: string;
readonly allowedOutputRoot?: string;
}> = [
{ name: 'non-.py notebook', notebookPath: '/work/nb.txt', outputPath: '/work/out.html' },
{ name: 'bare .py filename', notebookPath: '/work/.py', outputPath: '/work/out.html' },
{
name: 'trailing slash notebook',
notebookPath: '/work/nb.py/',
outputPath: '/work/out.html',
},
{ name: 'non-.html output', notebookPath: '/work/nb.py', outputPath: '/work/out.htm' },
{ name: 'bare .html filename', notebookPath: '/work/nb.py', outputPath: '/work/.html' },
{ name: 'relative notebook', notebookPath: 'research/nb.py', outputPath: '/work/out.html' },
{ name: 'relative output', notebookPath: '/work/nb.py', outputPath: './out.html' },
{ name: 'leading dash notebook', notebookPath: '-nb.py', outputPath: '/work/out.html' },
{ name: 'leading dash output', notebookPath: '/work/nb.py', outputPath: '--out.html' },
{ name: 'NUL in notebook', notebookPath: '/work/nb\0.py', outputPath: '/work/out.html' },
{ name: 'NUL in output', notebookPath: '/work/nb.py', outputPath: '/work/out\0.html' },
{
name: '.. escape outside allowedNotebookRoot',
notebookPath: '/work/notebooks/../secret.py',
outputPath: '/work/out/report.html',
allowedNotebookRoot: '/work/notebooks',
},
{
name: '.. escape outside allowedOutputRoot',
notebookPath: '/work/notebooks/nb.py',
outputPath: '/work/out/../evil.html',
allowedOutputRoot: '/work/out',
},
{
name: 'same-prefix sibling notebook root',
notebookPath: '/work/notebooks-other/nb.py',
outputPath: '/work/out/report.html',
allowedNotebookRoot: '/work/notebooks',
},
{
name: 'same-prefix sibling output root',
notebookPath: '/work/notebooks/nb.py',
outputPath: '/work/out-other/report.html',
allowedOutputRoot: '/work/out',
},
];
for (const tc of cases) {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
const { runner, calls } = createRecordingRunner(async () => ({
exitCode: 0,
stdout: '',
stderr: '',
}));
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: tc.notebookPath,
outputPath: tc.outputPath,
runner,
fs,
...(tc.allowedNotebookRoot !== undefined
? { allowedNotebookRoot: tc.allowedNotebookRoot }
: {}),
...(tc.allowedOutputRoot !== undefined
? { allowedOutputRoot: tc.allowedOutputRoot }
: {}),
}),
'INVALID_PATH'
);
expect(calls).toHaveLength(0);
}
});
test('rejects missing notebook or directory in place of notebook with NOTEBOOK_NOT_FOUND and zero runner calls', async () => {
for (const setup of ['missing', 'directory'] as const) {
const fs = new InMemoryNotebookFs();
if (setup === 'directory') {
fs.putDirectory('/work/nb.py');
}
const { runner, calls } = createRecordingRunner(async () => ({
exitCode: 0,
stdout: '',
stderr: '',
}));
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
}),
'NOTEBOOK_NOT_FOUND'
);
expect(calls).toHaveLength(0);
}
});
test('rejects invalid timeoutMs or marimoCommand with INVALID_OPTION and zero runner calls', async () => {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
const { runner, calls } = createRecordingRunner(async () => ({
exitCode: 0,
stdout: '',
stderr: '',
}));
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
timeoutMs: 0,
}),
'INVALID_OPTION'
);
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
marimoCommand: '-evil',
}),
'INVALID_OPTION'
);
expect(calls).toHaveLength(0);
});
});