38 lines
No EOL
1.1 KiB
TypeScript
38 lines
No EOL
1.1 KiB
TypeScript
import { diffLines } from "diff";
|
|
import { strict as assert } from "node:assert";
|
|
|
|
function color(text: string, c: "red" | "green") {
|
|
const codes = { red: '\x1b[31m', green: '\x1b[32m' };
|
|
return `${codes[c]}${text}\x1b[0m`;
|
|
}
|
|
|
|
/**Asserts two strings are equal and diffs them in the assertion error if they are
|
|
* not*/
|
|
export function assertStringEq(actual: string, expected: string, msg: string) {
|
|
if (actual === expected) {
|
|
return;
|
|
}
|
|
const diff = diffLines(actual, expected);
|
|
const assertionMsg = `${msg}\n` + diff
|
|
.map(part => {
|
|
if (!part.added && !part.removed) {
|
|
return part.value;
|
|
}
|
|
const prefix = part.added ? "+" : "-";
|
|
return color(`${prefix}${part.value}`, part.added ? "green" : "red");
|
|
})
|
|
.join("");
|
|
assert(actual === expected, assertionMsg);
|
|
}
|
|
|
|
/**Catches any p Promise throws and instead returns those in a tuple*/
|
|
export async function ptry<TRet, TError = Error>(
|
|
p: Promise<TRet>
|
|
): Promise<[TError, undefined] | [undefined, TRet]> {
|
|
try {
|
|
const result = await p;
|
|
return [undefined, result];
|
|
} catch (err) {
|
|
return [err as TError, undefined];
|
|
}
|
|
} |