mirror of
https://github.com/denoland/std.git
synced 2024-11-22 04:59:05 +00:00
refactor(assert,expect): use shared format.ts
and diff.ts
(#4592)
This commit is contained in:
parent
b2edca6441
commit
f57ac69735
@ -1,345 +0,0 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
import { diff, diffstr, DiffType } from "./_diff.ts";
|
||||
import { assertEquals } from "./assert_equals.ts";
|
||||
|
||||
Deno.test({
|
||||
name: "empty",
|
||||
fn() {
|
||||
assertEquals(diff([], []), []);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: '"a" vs "b"',
|
||||
fn() {
|
||||
assertEquals(diff(["a"], ["b"]), [
|
||||
{ type: DiffType.removed, value: "a" },
|
||||
{ type: DiffType.added, value: "b" },
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: '"a" vs "a"',
|
||||
fn() {
|
||||
assertEquals(diff(["a"], ["a"]), [{ type: DiffType.common, value: "a" }]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: '"a" vs ""',
|
||||
fn() {
|
||||
assertEquals(diff(["a"], []), [{ type: DiffType.removed, value: "a" }]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: '"" vs "a"',
|
||||
fn() {
|
||||
assertEquals(diff([], ["a"]), [{ type: DiffType.added, value: "a" }]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: '"a" vs "a, b"',
|
||||
fn() {
|
||||
assertEquals(diff(["a"], ["a", "b"]), [
|
||||
{ type: DiffType.common, value: "a" },
|
||||
{ type: DiffType.added, value: "b" },
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: '"strength" vs "string"',
|
||||
fn() {
|
||||
assertEquals(diff(Array.from("strength"), Array.from("string")), [
|
||||
{ type: DiffType.common, value: "s" },
|
||||
{ type: DiffType.common, value: "t" },
|
||||
{ type: DiffType.common, value: "r" },
|
||||
{ type: DiffType.removed, value: "e" },
|
||||
{ type: DiffType.added, value: "i" },
|
||||
{ type: DiffType.common, value: "n" },
|
||||
{ type: DiffType.common, value: "g" },
|
||||
{ type: DiffType.removed, value: "t" },
|
||||
{ type: DiffType.removed, value: "h" },
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: '"strength" vs ""',
|
||||
fn() {
|
||||
assertEquals(diff(Array.from("strength"), Array.from("")), [
|
||||
{ type: DiffType.removed, value: "s" },
|
||||
{ type: DiffType.removed, value: "t" },
|
||||
{ type: DiffType.removed, value: "r" },
|
||||
{ type: DiffType.removed, value: "e" },
|
||||
{ type: DiffType.removed, value: "n" },
|
||||
{ type: DiffType.removed, value: "g" },
|
||||
{ type: DiffType.removed, value: "t" },
|
||||
{ type: DiffType.removed, value: "h" },
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: '"" vs "strength"',
|
||||
fn() {
|
||||
assertEquals(diff(Array.from(""), Array.from("strength")), [
|
||||
{ type: DiffType.added, value: "s" },
|
||||
{ type: DiffType.added, value: "t" },
|
||||
{ type: DiffType.added, value: "r" },
|
||||
{ type: DiffType.added, value: "e" },
|
||||
{ type: DiffType.added, value: "n" },
|
||||
{ type: DiffType.added, value: "g" },
|
||||
{ type: DiffType.added, value: "t" },
|
||||
{ type: DiffType.added, value: "h" },
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: '"abc", "c" vs "abc", "bcd", "c"',
|
||||
fn() {
|
||||
assertEquals(diff(["abc", "c"], ["abc", "bcd", "c"]), [
|
||||
{ type: DiffType.common, value: "abc" },
|
||||
{ type: DiffType.added, value: "bcd" },
|
||||
{ type: DiffType.common, value: "c" },
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: '"a b c d" vs "a b x d e" (diffstr)',
|
||||
fn() {
|
||||
const diffResult = diffstr(
|
||||
[..."abcd"].join("\n"),
|
||||
[..."abxde"].join("\n"),
|
||||
);
|
||||
assertEquals(diffResult, [
|
||||
{ type: DiffType.common, value: "a\\n\n" },
|
||||
{ type: DiffType.common, value: "b\\n\n" },
|
||||
{
|
||||
type: DiffType.added,
|
||||
value: "x\\n\n",
|
||||
details: [
|
||||
{ type: DiffType.added, value: "x" },
|
||||
{ type: DiffType.common, value: "\\" },
|
||||
{ type: DiffType.common, value: "n" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: DiffType.added,
|
||||
value: "d\\n\n",
|
||||
details: [
|
||||
{ type: DiffType.common, value: "d" },
|
||||
{ type: DiffType.added, value: "\\" },
|
||||
{ type: DiffType.added, value: "n" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
{ type: DiffType.added, value: "e\n" },
|
||||
{
|
||||
type: DiffType.removed,
|
||||
value: "c\\n\n",
|
||||
details: [
|
||||
{ type: DiffType.removed, value: "c" },
|
||||
{ type: DiffType.common, value: "\\" },
|
||||
{ type: DiffType.common, value: "n" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: DiffType.removed,
|
||||
value: "d\n",
|
||||
details: [
|
||||
{ type: DiffType.common, value: "d" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: `"3.14" vs "2.71" (diffstr)`,
|
||||
fn() {
|
||||
const diffResult = diffstr("3.14", "2.71");
|
||||
assertEquals(diffResult, [
|
||||
{
|
||||
type: DiffType.removed,
|
||||
value: "3.14\n",
|
||||
details: [
|
||||
{
|
||||
type: DiffType.removed,
|
||||
value: "3",
|
||||
},
|
||||
{
|
||||
type: DiffType.common,
|
||||
value: ".",
|
||||
},
|
||||
{
|
||||
type: DiffType.removed,
|
||||
value: "14",
|
||||
},
|
||||
{
|
||||
type: DiffType.common,
|
||||
value: "\n",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: DiffType.added,
|
||||
value: "2.71\n",
|
||||
details: [
|
||||
{
|
||||
type: DiffType.added,
|
||||
value: "2",
|
||||
},
|
||||
{
|
||||
type: DiffType.common,
|
||||
value: ".",
|
||||
},
|
||||
{
|
||||
type: DiffType.added,
|
||||
value: "71",
|
||||
},
|
||||
{
|
||||
type: DiffType.common,
|
||||
value: "\n",
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: `single line "a b" vs "c d" (diffstr)`,
|
||||
fn() {
|
||||
const diffResult = diffstr("a b", "c d");
|
||||
assertEquals(diffResult, [
|
||||
{
|
||||
type: DiffType.removed,
|
||||
value: "a b\n",
|
||||
details: [
|
||||
{ type: DiffType.removed, value: "a" },
|
||||
{ type: DiffType.removed, value: " " },
|
||||
{ type: DiffType.removed, value: "b" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: DiffType.added,
|
||||
value: "c d\n",
|
||||
details: [
|
||||
{ type: DiffType.added, value: "c" },
|
||||
{ type: DiffType.added, value: " " },
|
||||
{ type: DiffType.added, value: "d" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: `single line, different word length "a bc" vs "cd e" (diffstr)`,
|
||||
fn() {
|
||||
const diffResult = diffstr("a bc", "cd e");
|
||||
assertEquals(diffResult, [
|
||||
{
|
||||
type: DiffType.removed,
|
||||
value: "a bc\n",
|
||||
details: [
|
||||
{ type: DiffType.removed, value: "a" },
|
||||
{ type: DiffType.removed, value: " " },
|
||||
{ type: DiffType.removed, value: "bc" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: DiffType.added,
|
||||
value: "cd e\n",
|
||||
details: [
|
||||
{ type: DiffType.added, value: "cd" },
|
||||
{ type: DiffType.added, value: " " },
|
||||
{ type: DiffType.added, value: "e" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: `"\\b\\f\\r\\t\\v\\n" vs "\\r\\n" (diffstr)`,
|
||||
fn() {
|
||||
const diffResult = diffstr("\b\f\r\t\v\n", "\r\n");
|
||||
assertEquals(diffResult, [
|
||||
{
|
||||
type: DiffType.removed,
|
||||
value: "\\b\\f\\r\\t\\v\\n\n",
|
||||
details: [
|
||||
{ type: DiffType.common, value: "\\" },
|
||||
{ type: DiffType.removed, value: "b" },
|
||||
{ type: DiffType.removed, value: "\\" },
|
||||
{ type: DiffType.removed, value: "f" },
|
||||
{ type: DiffType.removed, value: "\\" },
|
||||
{ type: DiffType.common, value: "r" },
|
||||
{ type: DiffType.common, value: "\\" },
|
||||
{ type: DiffType.removed, value: "t" },
|
||||
{ type: DiffType.removed, value: "\\" },
|
||||
{ type: DiffType.removed, value: "v" },
|
||||
{ type: DiffType.removed, value: "\\" },
|
||||
{ type: DiffType.common, value: "n" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: DiffType.added,
|
||||
value: "\\r\\n\r\n",
|
||||
details: [
|
||||
{ type: DiffType.common, value: "\\" },
|
||||
{ type: DiffType.common, value: "r" },
|
||||
{ type: DiffType.common, value: "\\" },
|
||||
{ type: DiffType.common, value: "n" },
|
||||
{ type: DiffType.added, value: "\r" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "multiline diff with more removed lines",
|
||||
fn() {
|
||||
const diffResult = diffstr("a\na", "e");
|
||||
assertEquals(diffResult, [
|
||||
{
|
||||
type: DiffType.removed,
|
||||
value: "a\\n\n",
|
||||
},
|
||||
{
|
||||
type: DiffType.removed,
|
||||
value: "a\n",
|
||||
details: [
|
||||
{ type: DiffType.removed, value: "a" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: DiffType.added,
|
||||
value: "e\n",
|
||||
details: [
|
||||
{ type: DiffType.added, value: "e" },
|
||||
{ type: DiffType.common, value: "\n" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
},
|
||||
});
|
@ -1,26 +0,0 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
|
||||
// This file been copied to `std/expect`.
|
||||
|
||||
/**
|
||||
* Converts the input into a string. Objects, Sets and Maps are sorted so as to
|
||||
* make tests less flaky
|
||||
* @param v Value to be formatted
|
||||
*/
|
||||
export function format(v: unknown): string {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const { Deno } = globalThis as any;
|
||||
return typeof Deno?.inspect === "function"
|
||||
? Deno.inspect(v, {
|
||||
depth: Infinity,
|
||||
sorted: true,
|
||||
trailingComma: true,
|
||||
compact: false,
|
||||
iterableLimit: Infinity,
|
||||
// getters should be true in assertEquals.
|
||||
getters: true,
|
||||
strAbbreviateSize: Infinity,
|
||||
})
|
||||
: `"${String(v).replace(/(?=["\\])/g, "\\")}"`;
|
||||
}
|
@ -1,100 +0,0 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
import { green, red, stripAnsiCode } from "../fmt/colors.ts";
|
||||
import { assertEquals, assertThrows } from "../assert/mod.ts";
|
||||
import { format } from "./_format.ts";
|
||||
|
||||
// This file been copied to `std/expect`.
|
||||
|
||||
Deno.test("format() generates correct diffs for strings", () => {
|
||||
assertThrows(
|
||||
() => {
|
||||
assertEquals([..."abcd"].join("\n"), [..."abxde"].join("\n"));
|
||||
},
|
||||
Error,
|
||||
`
|
||||
a\\n
|
||||
b\\n
|
||||
${green("+ x")}\\n
|
||||
${green("+ d")}\\n
|
||||
${green("+ e")}
|
||||
${red("- c")}\\n
|
||||
${red("- d")}
|
||||
`,
|
||||
);
|
||||
});
|
||||
|
||||
// Check that the diff formatter overrides some default behaviours of
|
||||
// `Deno.inspect()` which are problematic for diffing.
|
||||
Deno.test("format() overrides default behaviours of Deno.inspect", async (t) => {
|
||||
// Wraps objects into multiple lines even when they are small. Prints trailing
|
||||
// commas.
|
||||
await t.step(
|
||||
"fromat() always wraps objects into multiple lines and prints trailing commas",
|
||||
() =>
|
||||
assertEquals(
|
||||
stripAnsiCode(format({ a: 1, b: 2 })),
|
||||
`{
|
||||
a: 1,
|
||||
b: 2,
|
||||
}`,
|
||||
),
|
||||
);
|
||||
|
||||
await t.step("format() wraps Object with getters", () =>
|
||||
assertEquals(
|
||||
format(Object.defineProperty({}, "a", {
|
||||
enumerable: true,
|
||||
get() {
|
||||
return 1;
|
||||
},
|
||||
})),
|
||||
`{
|
||||
a: [Getter: 1],
|
||||
}`,
|
||||
));
|
||||
|
||||
await t.step("format() wraps nested small objects", () =>
|
||||
assertEquals(
|
||||
stripAnsiCode(format([{ x: { a: 1, b: 2 }, y: ["a", "b"] }])),
|
||||
`[
|
||||
{
|
||||
x: {
|
||||
a: 1,
|
||||
b: 2,
|
||||
},
|
||||
y: [
|
||||
"a",
|
||||
"b",
|
||||
],
|
||||
},
|
||||
]`,
|
||||
));
|
||||
|
||||
// Grouping is disabled.
|
||||
await t.step("format() disables grouping", () =>
|
||||
assertEquals(
|
||||
stripAnsiCode(format(["i", "i", "i", "i", "i", "i", "i"])),
|
||||
`[
|
||||
"i",
|
||||
"i",
|
||||
"i",
|
||||
"i",
|
||||
"i",
|
||||
"i",
|
||||
"i",
|
||||
]`,
|
||||
));
|
||||
});
|
||||
|
||||
Deno.test("format() doesn't truncate long strings in object", () => {
|
||||
const str = format({
|
||||
foo:
|
||||
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
|
||||
});
|
||||
assertEquals(
|
||||
str,
|
||||
`{
|
||||
foo: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
|
||||
}`,
|
||||
);
|
||||
});
|
@ -1,7 +1,7 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
import { equal } from "./equal.ts";
|
||||
import { format } from "./_format.ts";
|
||||
import { format } from "../internal/format.ts";
|
||||
import { AssertionError } from "./assertion_error.ts";
|
||||
|
||||
/** An array-like object (`Array`, `Uint8Array`, `NodeList`, etc.) that is not a string */
|
||||
|
@ -1,10 +1,9 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
import { equal } from "./equal.ts";
|
||||
import { format } from "./_format.ts";
|
||||
import { buildMessage, diff, diffstr, format } from "../internal/mod.ts";
|
||||
import { AssertionError } from "./assertion_error.ts";
|
||||
import { red } from "../fmt/colors.ts";
|
||||
import { buildMessage, diff, diffstr } from "./_diff.ts";
|
||||
import { CAN_NOT_DISPLAY } from "./_constants.ts";
|
||||
|
||||
/**
|
||||
|
@ -1,6 +1,6 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
import { format } from "./_format.ts";
|
||||
import { format } from "../internal/format.ts";
|
||||
import { AssertionError } from "./assertion_error.ts";
|
||||
|
||||
/**
|
||||
|
@ -1,6 +1,6 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
import { format } from "./_format.ts";
|
||||
import { format } from "../internal/format.ts";
|
||||
import { AssertionError } from "./assertion_error.ts";
|
||||
|
||||
/**
|
||||
|
@ -1,6 +1,6 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
import { format } from "./_format.ts";
|
||||
import { format } from "../internal/format.ts";
|
||||
import { AssertionError } from "./assertion_error.ts";
|
||||
|
||||
/**
|
||||
|
@ -1,6 +1,6 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
import { format } from "./_format.ts";
|
||||
import { format } from "../internal/format.ts";
|
||||
import { AssertionError } from "./assertion_error.ts";
|
||||
|
||||
/**
|
||||
|
@ -1,7 +1,7 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
import { AssertionError } from "./assertion_error.ts";
|
||||
import { format } from "./_format.ts";
|
||||
import { format } from "../internal/format.ts";
|
||||
|
||||
/**
|
||||
* Make an assertion that `actual` and `expected` are not strictly equal.
|
||||
|
@ -1,8 +1,7 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
import { format } from "./_format.ts";
|
||||
import { buildMessage, diff, diffstr, format } from "../internal/mod.ts";
|
||||
import { AssertionError } from "./assertion_error.ts";
|
||||
import { buildMessage, diff, diffstr } from "./_diff.ts";
|
||||
import { CAN_NOT_DISPLAY } from "./_constants.ts";
|
||||
import { red } from "../fmt/colors.ts";
|
||||
|
||||
|
@ -2,8 +2,7 @@
|
||||
|
||||
import { red } from "../fmt/colors.ts";
|
||||
import { CAN_NOT_DISPLAY } from "./_constants.ts";
|
||||
import { buildMessage, diff, diffstr } from "./_diff.ts";
|
||||
import { format } from "./_format.ts";
|
||||
import { buildMessage, diff, diffstr, format } from "../internal/mod.ts";
|
||||
import type { EqualOptions } from "./_types.ts";
|
||||
|
||||
type EqualErrorMessageOptions = Pick<
|
||||
|
465
expect/_diff.ts
465
expect/_diff.ts
@ -1,465 +0,0 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
|
||||
import {
|
||||
bgGreen,
|
||||
bgRed,
|
||||
bold,
|
||||
gray,
|
||||
green,
|
||||
red,
|
||||
white,
|
||||
} from "../fmt/colors.ts";
|
||||
|
||||
interface FarthestPoint {
|
||||
y: number;
|
||||
id: number;
|
||||
}
|
||||
|
||||
export const DiffType = {
|
||||
removed: "removed",
|
||||
common: "common",
|
||||
added: "added",
|
||||
} as const;
|
||||
|
||||
export type DiffType = keyof typeof DiffType;
|
||||
|
||||
export interface DiffResult<T> {
|
||||
type: DiffType;
|
||||
value: T;
|
||||
details?: Array<DiffResult<T>>;
|
||||
}
|
||||
|
||||
const REMOVED = 1;
|
||||
const COMMON = 2;
|
||||
const ADDED = 3;
|
||||
|
||||
function createCommon<T>(A: T[], B: T[], reverse?: boolean): T[] {
|
||||
const common: T[] = [];
|
||||
if (A.length === 0 || B.length === 0) return [];
|
||||
for (let i = 0; i < Math.min(A.length, B.length); i += 1) {
|
||||
const a = reverse ? A[A.length - i - 1] : A[i];
|
||||
const b = reverse ? B[B.length - i - 1] : B[i];
|
||||
if (a !== undefined && a === b) {
|
||||
common.push(a);
|
||||
} else {
|
||||
return common;
|
||||
}
|
||||
}
|
||||
return common;
|
||||
}
|
||||
|
||||
function ensureDefined<T>(item?: T): T {
|
||||
if (item === undefined) {
|
||||
throw Error("Unexpected missing FarthestPoint");
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the differences between the actual and expected values
|
||||
* @param A Actual value
|
||||
* @param B Expected value
|
||||
*/
|
||||
export function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> {
|
||||
const prefixCommon = createCommon(A, B);
|
||||
const suffixCommon = createCommon(
|
||||
A.slice(prefixCommon.length),
|
||||
B.slice(prefixCommon.length),
|
||||
true,
|
||||
).reverse();
|
||||
A = suffixCommon.length
|
||||
? A.slice(prefixCommon.length, -suffixCommon.length)
|
||||
: A.slice(prefixCommon.length);
|
||||
B = suffixCommon.length
|
||||
? B.slice(prefixCommon.length, -suffixCommon.length)
|
||||
: B.slice(prefixCommon.length);
|
||||
const swapped = B.length > A.length;
|
||||
[A, B] = swapped ? [B, A] : [A, B];
|
||||
const M = A.length;
|
||||
const N = B.length;
|
||||
if (!M && !N && !suffixCommon.length && !prefixCommon.length) return [];
|
||||
if (!N) {
|
||||
return [
|
||||
...prefixCommon.map(
|
||||
(c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }),
|
||||
),
|
||||
...A.map(
|
||||
(a): DiffResult<typeof a> => ({
|
||||
type: swapped ? DiffType.added : DiffType.removed,
|
||||
value: a,
|
||||
}),
|
||||
),
|
||||
...suffixCommon.map(
|
||||
(c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }),
|
||||
),
|
||||
];
|
||||
}
|
||||
const offset = N;
|
||||
const delta = M - N;
|
||||
const size = M + N + 1;
|
||||
const fp: FarthestPoint[] = Array.from(
|
||||
{ length: size },
|
||||
() => ({ y: -1, id: -1 }),
|
||||
);
|
||||
|
||||
/**
|
||||
* INFO:
|
||||
* This buffer is used to save memory and improve performance.
|
||||
* The first half is used to save route and last half is used to save diff
|
||||
* type.
|
||||
* This is because, when I kept new uint8array area to save type,performance
|
||||
* worsened.
|
||||
*/
|
||||
const routes = new Uint32Array((M * N + size + 1) * 2);
|
||||
const diffTypesPtrOffset = routes.length / 2;
|
||||
let ptr = 0;
|
||||
let p = -1;
|
||||
|
||||
function backTrace<T>(
|
||||
A: T[],
|
||||
B: T[],
|
||||
current: FarthestPoint,
|
||||
swapped: boolean,
|
||||
): Array<{
|
||||
type: DiffType;
|
||||
value: T;
|
||||
}> {
|
||||
const M = A.length;
|
||||
const N = B.length;
|
||||
const result: { type: DiffType; value: T }[] = [];
|
||||
let a = M - 1;
|
||||
let b = N - 1;
|
||||
let j = routes[current.id];
|
||||
let type = routes[current.id + diffTypesPtrOffset];
|
||||
while (true) {
|
||||
if (!j && !type) break;
|
||||
const prev = j!;
|
||||
if (type === REMOVED) {
|
||||
result.unshift({
|
||||
type: swapped ? DiffType.removed : DiffType.added,
|
||||
value: B[b]!,
|
||||
});
|
||||
b -= 1;
|
||||
} else if (type === ADDED) {
|
||||
result.unshift({
|
||||
type: swapped ? DiffType.added : DiffType.removed,
|
||||
value: A[a]!,
|
||||
});
|
||||
a -= 1;
|
||||
} else {
|
||||
result.unshift({ type: DiffType.common, value: A[a]! });
|
||||
a -= 1;
|
||||
b -= 1;
|
||||
}
|
||||
j = routes[prev];
|
||||
type = routes[prev + diffTypesPtrOffset];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function createFP(
|
||||
slide: FarthestPoint | undefined,
|
||||
down: FarthestPoint | undefined,
|
||||
k: number,
|
||||
M: number,
|
||||
): FarthestPoint {
|
||||
if (slide && slide.y === -1 && down && down.y === -1) {
|
||||
return { y: 0, id: 0 };
|
||||
}
|
||||
const isAdding = (down?.y === -1) ||
|
||||
k === M ||
|
||||
(slide?.y || 0) > (down?.y || 0) + 1;
|
||||
if (slide && isAdding) {
|
||||
const prev = slide.id;
|
||||
ptr++;
|
||||
routes[ptr] = prev;
|
||||
routes[ptr + diffTypesPtrOffset] = ADDED;
|
||||
return { y: slide.y, id: ptr };
|
||||
} else if (down && !isAdding) {
|
||||
const prev = down.id;
|
||||
ptr++;
|
||||
routes[ptr] = prev;
|
||||
routes[ptr + diffTypesPtrOffset] = REMOVED;
|
||||
return { y: down.y + 1, id: ptr };
|
||||
} else {
|
||||
throw new Error("Unexpected missing FarthestPoint");
|
||||
}
|
||||
}
|
||||
|
||||
function snake<T>(
|
||||
k: number,
|
||||
slide: FarthestPoint | undefined,
|
||||
down: FarthestPoint | undefined,
|
||||
_offset: number,
|
||||
A: T[],
|
||||
B: T[],
|
||||
): FarthestPoint {
|
||||
const M = A.length;
|
||||
const N = B.length;
|
||||
if (k < -N || M < k) return { y: -1, id: -1 };
|
||||
const fp = createFP(slide, down, k, M);
|
||||
while (fp.y + k < M && fp.y < N && A[fp.y + k] === B[fp.y]) {
|
||||
const prev = fp.id;
|
||||
ptr++;
|
||||
fp.id = ptr;
|
||||
fp.y += 1;
|
||||
routes[ptr] = prev;
|
||||
routes[ptr + diffTypesPtrOffset] = COMMON;
|
||||
}
|
||||
return fp;
|
||||
}
|
||||
|
||||
let currentFP = ensureDefined<FarthestPoint>(fp[delta + offset]);
|
||||
while (currentFP && currentFP.y < N) {
|
||||
p = p + 1;
|
||||
for (let k = -p; k < delta; ++k) {
|
||||
fp[k + offset] = snake(
|
||||
k,
|
||||
fp[k - 1 + offset],
|
||||
fp[k + 1 + offset],
|
||||
offset,
|
||||
A,
|
||||
B,
|
||||
);
|
||||
}
|
||||
for (let k = delta + p; k > delta; --k) {
|
||||
fp[k + offset] = snake(
|
||||
k,
|
||||
fp[k - 1 + offset],
|
||||
fp[k + 1 + offset],
|
||||
offset,
|
||||
A,
|
||||
B,
|
||||
);
|
||||
}
|
||||
fp[delta + offset] = snake(
|
||||
delta,
|
||||
fp[delta - 1 + offset],
|
||||
fp[delta + 1 + offset],
|
||||
offset,
|
||||
A,
|
||||
B,
|
||||
);
|
||||
currentFP = ensureDefined(fp[delta + offset]);
|
||||
}
|
||||
return [
|
||||
...prefixCommon.map(
|
||||
(c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }),
|
||||
),
|
||||
...backTrace(A, B, currentFP, swapped),
|
||||
...suffixCommon.map(
|
||||
(c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the differences between the actual and expected strings
|
||||
* Partially inspired from https://github.com/kpdecker/jsdiff
|
||||
* @param A Actual string
|
||||
* @param B Expected string
|
||||
*/
|
||||
export function diffstr(A: string, B: string) {
|
||||
function unescape(string: string): string {
|
||||
// unescape invisible characters.
|
||||
// ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences
|
||||
return string
|
||||
.replaceAll("\b", "\\b")
|
||||
.replaceAll("\f", "\\f")
|
||||
.replaceAll("\t", "\\t")
|
||||
.replaceAll("\v", "\\v")
|
||||
.replaceAll( // does not remove line breaks
|
||||
/\r\n|\r|\n/g,
|
||||
(str) => str === "\r" ? "\\r" : str === "\n" ? "\\n\n" : "\\r\\n\r\n",
|
||||
);
|
||||
}
|
||||
|
||||
function tokenize(string: string, { wordDiff = false } = {}): string[] {
|
||||
if (wordDiff) {
|
||||
// Split string on whitespace symbols
|
||||
const tokens = string.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);
|
||||
// Extended Latin character set
|
||||
const words =
|
||||
/^[a-zA-Z\u{C0}-\u{FF}\u{D8}-\u{F6}\u{F8}-\u{2C6}\u{2C8}-\u{2D7}\u{2DE}-\u{2FF}\u{1E00}-\u{1EFF}]+$/u;
|
||||
|
||||
// Join boundary splits that we do not consider to be boundaries and merge empty strings surrounded by word chars
|
||||
for (let i = 0; i < tokens.length - 1; i++) {
|
||||
const token = tokens[i];
|
||||
const tokenPlusTwo = tokens[i + 2];
|
||||
if (
|
||||
!tokens[i + 1] &&
|
||||
token &&
|
||||
tokenPlusTwo &&
|
||||
words.test(token) &&
|
||||
words.test(tokenPlusTwo)
|
||||
) {
|
||||
tokens[i] += tokenPlusTwo;
|
||||
tokens.splice(i + 1, 2);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
return tokens.filter((token) => token);
|
||||
} else {
|
||||
// Split string on new lines symbols
|
||||
const tokens: string[] = [];
|
||||
const lines = string.split(/(\n|\r\n)/);
|
||||
|
||||
// Ignore final empty token when text ends with a newline
|
||||
if (!lines[lines.length - 1]) {
|
||||
lines.pop();
|
||||
}
|
||||
|
||||
// Merge the content and line separators into single tokens
|
||||
for (const [i, line] of lines.entries()) {
|
||||
if (i % 2) {
|
||||
tokens[tokens.length - 1] += line;
|
||||
} else {
|
||||
tokens.push(line);
|
||||
}
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
}
|
||||
|
||||
// Create details by filtering relevant word-diff for current line
|
||||
// and merge "space-diff" if surrounded by word-diff for cleaner displays
|
||||
function createDetails(
|
||||
line: DiffResult<string>,
|
||||
tokens: Array<DiffResult<string>>,
|
||||
) {
|
||||
return tokens.filter(({ type }) =>
|
||||
type === line.type || type === DiffType.common
|
||||
).map((result, i, t) => {
|
||||
const token = t[i - 1];
|
||||
if (
|
||||
(result.type === DiffType.common) && token &&
|
||||
(token.type === t[i + 1]?.type) && /\s+/.test(result.value)
|
||||
) {
|
||||
return {
|
||||
...result,
|
||||
type: token.type,
|
||||
};
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
// Compute multi-line diff
|
||||
const diffResult = diff(
|
||||
tokenize(`${unescape(A)}\n`),
|
||||
tokenize(`${unescape(B)}\n`),
|
||||
);
|
||||
|
||||
const added = [];
|
||||
const removed = [];
|
||||
for (const result of diffResult) {
|
||||
if (result.type === DiffType.added) {
|
||||
added.push(result);
|
||||
}
|
||||
if (result.type === DiffType.removed) {
|
||||
removed.push(result);
|
||||
}
|
||||
}
|
||||
|
||||
// Compute word-diff
|
||||
const hasMoreRemovedLines = added.length < removed.length;
|
||||
const aLines = hasMoreRemovedLines ? added : removed;
|
||||
const bLines = hasMoreRemovedLines ? removed : added;
|
||||
for (const a of aLines) {
|
||||
let tokens = [] as Array<DiffResult<string>>;
|
||||
let b: undefined | DiffResult<string>;
|
||||
// Search another diff line with at least one common token
|
||||
while (bLines.length) {
|
||||
b = bLines.shift();
|
||||
const tokenized = [
|
||||
tokenize(a.value, { wordDiff: true }),
|
||||
tokenize(b?.value ?? "", { wordDiff: true }),
|
||||
] as [string[], string[]];
|
||||
if (hasMoreRemovedLines) tokenized.reverse();
|
||||
tokens = diff(tokenized[0], tokenized[1]);
|
||||
if (
|
||||
tokens.some(({ type, value }) =>
|
||||
type === DiffType.common && value.trim().length
|
||||
)
|
||||
) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Register word-diff details
|
||||
a.details = createDetails(a, tokens);
|
||||
if (b) {
|
||||
b.details = createDetails(b, tokens);
|
||||
}
|
||||
}
|
||||
|
||||
return diffResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Colors the output of assertion diffs
|
||||
* @param diffType Difference type, either added or removed
|
||||
*/
|
||||
function createColor(
|
||||
diffType: DiffType,
|
||||
{ background = false } = {},
|
||||
): (s: string) => string {
|
||||
// TODO(@littledivy): Remove this when we can detect
|
||||
// true color terminals.
|
||||
// https://github.com/denoland/deno_std/issues/2575
|
||||
background = false;
|
||||
switch (diffType) {
|
||||
case DiffType.added:
|
||||
return (s: string): string =>
|
||||
background ? bgGreen(white(s)) : green(bold(s));
|
||||
case DiffType.removed:
|
||||
return (s: string): string => background ? bgRed(white(s)) : red(bold(s));
|
||||
default:
|
||||
return white;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefixes `+` or `-` in diff output
|
||||
* @param diffType Difference type, either added or removed
|
||||
*/
|
||||
function createSign(diffType: DiffType): string {
|
||||
switch (diffType) {
|
||||
case DiffType.added:
|
||||
return "+ ";
|
||||
case DiffType.removed:
|
||||
return "- ";
|
||||
default:
|
||||
return " ";
|
||||
}
|
||||
}
|
||||
|
||||
export function buildMessage(
|
||||
diffResult: ReadonlyArray<DiffResult<string>>,
|
||||
{ stringDiff = false } = {},
|
||||
): string[] {
|
||||
const messages: string[] = [];
|
||||
const diffMessages: string[] = [];
|
||||
messages.push("");
|
||||
messages.push("");
|
||||
messages.push(
|
||||
` ${gray(bold("[Diff]"))} ${red(bold("Actual"))} / ${
|
||||
green(bold("Expected"))
|
||||
}`,
|
||||
);
|
||||
messages.push("");
|
||||
messages.push("");
|
||||
diffResult.forEach((result: DiffResult<string>) => {
|
||||
const c = createColor(result.type);
|
||||
const line = result.details?.map((detail) =>
|
||||
detail.type !== DiffType.common
|
||||
? createColor(detail.type, { background: true })(detail.value)
|
||||
: detail.value
|
||||
).join("") ?? result.value;
|
||||
diffMessages.push(c(`${createSign(result.type)}${line}`));
|
||||
});
|
||||
messages.push(...(stringDiff ? [diffMessages.join("")] : diffMessages));
|
||||
messages.push("");
|
||||
|
||||
return messages;
|
||||
}
|
@ -13,7 +13,7 @@ import { AssertionError } from "../assert/assertion_error.ts";
|
||||
import { assertEquals } from "./_assert_equals.ts";
|
||||
import { assertNotEquals } from "./_assert_not_equals.ts";
|
||||
import { equal } from "./_equal.ts";
|
||||
import { format } from "./_format.ts";
|
||||
import { format } from "../internal/format.ts";
|
||||
import type { AnyConstructor, MatcherContext, MatchResult } from "./_types.ts";
|
||||
import { getMockCalls } from "./_mock_util.ts";
|
||||
import { inspectArg, inspectArgs } from "./_inspect_args.ts";
|
||||
|
@ -1,9 +1,7 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
|
||||
// This file is copied from `std/assert`.
|
||||
|
||||
import { diff, diffstr, DiffType } from "./_diff.ts";
|
||||
import { assertEquals } from "./_assert_equals.ts";
|
||||
import { diff, diffstr, DiffType } from "./diff.ts";
|
||||
import { assertEquals } from "../assert/assert_equals.ts";
|
||||
|
||||
Deno.test({
|
||||
name: "diff() with empty values",
|
@ -1,8 +1,6 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
|
||||
// This file is copied from `std/assert`.
|
||||
|
||||
/**
|
||||
* Converts the input into a string. Objects, Sets and Maps are sorted so as to
|
||||
* make tests less flaky
|
@ -1,9 +1,7 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
import { green, red, stripAnsiCode } from "../fmt/colors.ts";
|
||||
import { assertEquals, assertThrows } from "../assert/mod.ts";
|
||||
import { format } from "./_format.ts";
|
||||
|
||||
// This file is copied from `std/assert`.
|
||||
import { format } from "./format.ts";
|
||||
|
||||
Deno.test("format() generates correct diffs for strings", () => {
|
||||
assertThrows(
|
11
internal/mod.ts
Normal file
11
internal/mod.ts
Normal file
@ -0,0 +1,11 @@
|
||||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
||||
// This module is browser compatible.
|
||||
/**
|
||||
* Internal utilities for the public API of the Deno Standard Library.
|
||||
*
|
||||
* Note: this module is for internal use only and should not be used directly.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
export * from "./format.ts";
|
||||
export * from "./diff.ts";
|
Loading…
Reference in New Issue
Block a user