1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-29 02:29:06 -05:00
denoland-deno/testing/pretty.ts

85 lines
2 KiB
TypeScript
Raw Normal View History

2019-02-15 11:11:55 -05:00
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
2019-03-06 16:39:50 -05:00
import { equal } from "./asserts.ts";
2019-02-15 11:11:55 -05:00
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-04 19:53:35 -05:00
function createColor(diffType: DiffType): (s: string) => string {
2019-02-15 11:11:55 -05:00
switch (diffType) {
2019-03-05 14:58:28 -05:00
case DiffType.added:
2019-04-24 07:41:23 -04:00
return (s: string): string => green(bold(s));
2019-03-05 14:58:28 -05:00
case DiffType.removed:
2019-04-24 07:41:23 -04:00
return (s: string): string => red(bold(s));
2019-02-15 11:11:55 -05:00
default:
return white;
}
}
2019-03-04 19:53:35 -05:00
function createSign(diffType: DiffType): string {
2019-02-15 11:11:55 -05:00
switch (diffType) {
2019-03-05 14:58:28 -05:00
case DiffType.added:
2019-02-15 11:11:55 -05:00
return "+ ";
2019-03-05 14:58:28 -05:00
case DiffType.removed:
2019-02-15 11:11:55 -05:00
return "- ";
default:
return " ";
}
}
2019-03-04 19:53:35 -05:00
function buildMessage(diffResult: ReadonlyArray<DiffResult<string>>): string[] {
2019-02-15 11:11:55 -05:00
const messages = [];
messages.push("");
messages.push("");
messages.push(
` ${gray(bold("[Diff]"))} ${red(bold("Left"))} / ${green(bold("Right"))}`
);
messages.push("");
messages.push("");
2019-04-24 07:41:23 -04:00
diffResult.forEach(
(result: DiffResult<string>): void => {
const c = createColor(result.type);
messages.push(c(`${createSign(result.type)}${result.value}`));
}
);
2019-02-15 11:11:55 -05:00
messages.push("");
return messages;
}
export function assertEquals(
actual: unknown,
expected: unknown,
msg?: string
): void {
2019-02-15 11:11:55 -05: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-15 11:11:55 -05:00
throw new Error(message);
}