Skip to content

Instantly share code, notes, and snippets.

@michaelfig
Created February 26, 2023 18:48
Show Gist options
  • Save michaelfig/ddd5b5f9cfa3356f8046496334e8eb57 to your computer and use it in GitHub Desktop.
Save michaelfig/ddd5b5f9cfa3356f8046496334e8eb57 to your computer and use it in GitHub Desktop.
Using AVA snapshots to check command output files
// `yarn add globby` in `endo`
// Put this file in `endo/packages/captp/test/test-types.js`
//
// `cd packages/captp` and run `yarn test test/test-types.js`
// `yarn test -u test/test-types.js` to update the snapshots
//
// Snapshots are kept in test/snapshots/*
import test from 'ava';
import fs from 'node:fs';
import { spawn } from 'node:child_process';
import path from 'node:path';
import { globby } from 'globby';
const pspawn = (cmd, args, { logFile, ...opts } = {}) =>
new Promise(resolve => {
const proc = spawn(cmd, args, opts);
if (logFile) {
proc.stdout.on('data', data => fs.appendFileSync(logFile, data));
proc.stderr.on('data', data => fs.appendFileSync(logFile, data));
}
proc.on('close', code => resolve(code));
});
const annoType = async (...args) => {
let tmpdir;
try {
tmpdir = await fs.promises.mkdtemp('anno-type-');
const logFile = path.join(tmpdir, 'anno-type.log');
await fs.promises.writeFile(`${logFile}.js`, `// timestamp: ${Date.now()}\n`); // REMOVE
const code = await pspawn(
'/bin/echo', // 'yarn'
['anno-type', '-abc', `--output=${tmpdir}`, ...args],
{ logFile, cwd: process.cwd(), stdio: ['ignore', 'pipe', 'pipe'] }
);
if (code !== 0) {
throw Error(`anno-type exited with code ${code}`);
}
} catch (e) {
// Keep the temporary directory around for debugging.
console.error(`Error executing with output in ${tmpdir}:`, e);
throw e;
}
return tmpdir;
};
const compareGlob = async (t, dir, patterns, desc) => {
const d = desc ? txt => `${txt}: ${desc}` : txt => txt;
const files = await globby(patterns.map(pat => path.posix.join(dir, pat)));
const relents = files.sort().map(f => [f, path.posix.relative(dir, f)]);
t.snapshot(relents.map(([_k, v]) => v), d(`output filenames`));
for (const [file, relfile] of relents) {
const buf = await fs.promises.readFile(file);
const content = buf.toString('utf-8');
t.snapshot(content, d(`content of ${relfile}`));
}
};
test('check something', async t => {
const tmpDir = await annoType('foo', 'bar');
await compareGlob(t, tmpDir, ['**/*.js'], `foo and bar`);
await fs.promises.rm(tmpDir, { recursive: true });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment