Skip to content

Instantly share code, notes, and snippets.

@takkaria
Created December 3, 2021 14:07
Show Gist options
  • Save takkaria/95a75bc7043e78c77f7d521360ce8b26 to your computer and use it in GitHub Desktop.
Save takkaria/95a75bc7043e78c77f7d521360ce8b26 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
const { readdirSync, readFileSync } = require('fs');
const model = require('../mhep/dev/static/dev/js/model');
const datasets = require('../mhep/dev/static/dev/js/model-datasets');
const process = require('process');
function lines(obj, prefix = '.') {
return Object.entries(obj).flatMap(([ k, v ]) => {
if (typeof v === 'object' && v !== null ) {
return lines(v, prefix + k + '.');
} else {
return { key: `${prefix}${k}`, value: v };
}
});
}
function nearlyEqual(left, right) {
if (left === right) {
return true;
} else if (typeof left === 'number' && typeof right === 'number') {
if (isNaN(left) && isNaN(right)) {
// NaNs are otherwise not equal
return true;
} else {
// Tolerate some floating point discrepancy
return Math.abs(left - right) <= 0.0000000001;
}
} else {
return false;
}
}
function diff(left, right) {
const lleft = lines(left);
const lright = lines(right);
const mleft = new Map(lleft.map(e => [ e.key, e.value ]));
const mright = new Map(lright.map(e => [ e.key, e.value ]));
const allKeys = new Set(lleft.concat(lright).map(e => e.key));
let difference = false;
for (let e of allKeys) {
const lval = mleft.get(e);
const rval = mright.get(e);
if (!nearlyEqual(lval, rval)) {
if (lval !== undefined && rval !== undefined) {
console.log(`! ${e} = ${lval} -> ${rval}`);
difference = true;
} else {
if (lval !== undefined) {
console.log(`- ${e} = ${lval}`);
difference = true;
}
if (rval !== undefined) {
console.log(`+ ${e} = ${rval}`);
difference = true;
}
}
}
}
return difference;
}
function getFileNames(path) {
const files = readdirSync(path);
return files.filter(name => name.includes('.in.json'));
}
const files = getFileNames('testdata/');
for (let inFile of files) {
const outFile = inFile.replace('.in.', '.out.');
const input = JSON.parse(readFileSync('testdata/' + inFile));
const expected = JSON.parse(readFileSync('testdata/' + outFile));
const actual = JSON.parse(JSON.stringify(model.runAll(input, datasets)));
if (diff(expected, actual)) {
console.error(`FAIL ${inFile}`);
process.exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment