1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-16 19:04:02 -05:00
denoland-deno/testing/pretty.ts

83 lines
1.9 KiB
TypeScript
Raw Normal View History

2019-02-16 01:11:55 +09:00
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { equal } from "./mod.ts";
import { red, green, white, gray, bold } from "../colors/mod.ts";
import diff, { DiffType, DiffResult } from "./diff.ts";
import { format } from "./format.ts";
const CAN_NOT_DISPLAY = "[Cannot display]";
function createStr(v: unknown): string {
try {
return format(v);
} catch (e) {
return red(CAN_NOT_DISPLAY);
}
}
2019-03-05 11:53:35 +11:00
function createColor(diffType: DiffType): (s: string) => string {
2019-02-16 01:11:55 +09:00
switch (diffType) {
2019-03-05 20:58:28 +01:00
case DiffType.added:
2019-02-16 01:11:55 +09:00
return (s: string) => green(bold(s));
2019-03-05 20:58:28 +01:00
case DiffType.removed:
2019-02-16 01:11:55 +09:00
return (s: string) => red(bold(s));
default:
return white;
}
}
2019-03-05 11:53:35 +11:00
function createSign(diffType: DiffType): string {
2019-02-16 01:11:55 +09:00
switch (diffType) {
2019-03-05 20:58:28 +01:00
case DiffType.added:
2019-02-16 01:11:55 +09:00
return "+ ";
2019-03-05 20:58:28 +01:00
case DiffType.removed:
2019-02-16 01:11:55 +09:00
return "- ";
default:
return " ";
}
}
2019-03-05 11:53:35 +11:00
function buildMessage(diffResult: ReadonlyArray<DiffResult<string>>): string[] {
2019-02-16 01:11:55 +09:00
const messages = [];
messages.push("");
messages.push("");
messages.push(
` ${gray(bold("[Diff]"))} ${red(bold("Left"))} / ${green(bold("Right"))}`
);
messages.push("");
messages.push("");
diffResult.forEach((result: DiffResult<string>) => {
const c = createColor(result.type);
messages.push(c(`${createSign(result.type)}${result.value}`));
});
messages.push("");
return messages;
}
export function assertEqual(
actual: unknown,
expected: unknown,
msg?: string
): void {
2019-02-16 01:11:55 +09:00
if (equal(actual, expected)) {
return;
}
let message = "";
const actualString = createStr(actual);
const expectedString = createStr(expected);
try {
const diffResult = diff(
actualString.split("\n"),
expectedString.split("\n")
);
message = buildMessage(diffResult).join("\n");
} catch (e) {
message = `\n${red(CAN_NOT_DISPLAY)} + \n\n`;
}
if (msg) {
message = msg;
}
2019-02-16 01:11:55 +09:00
throw new Error(message);
}