Debian Codegraph @

addons/web/static/lib/hoot/tests/hoot_utils.test.js

raw
1 /** @odoo-module */
2
3 import { describe, expect, test } from "@odoo/hoot";
4 import { queryOne } from "@odoo/hoot-dom";
5 import { isInstanceOf, isIterable } from "@web/../lib/hoot-dom/hoot_dom_utils";
6 import {
7 deepCopy,
8 deepEqual,
9 formatHumanReadable,
10 formatTechnical,
11 generateHash,
12 levenshtein,
13 lookup,
14 match,
15 parseQuery,
16 S_CIRCULAR,
17 title,
18 toExplicitString,
19 } from "../hoot_utils";
20 import { mountForTest, parseUrl } from "./local_helpers";
21
22 const recursive = {};
23 recursive.self = recursive;
24
25 describe(parseUrl(import.meta.url), () => {
26 test("deepCopy", () => {
27 expect(deepCopy(true)).toEqual(true);
28 expect(deepCopy(false)).toEqual(false);
29 expect(deepCopy(null)).toEqual(null);
30 expect(deepCopy(recursive)).toEqual({ self: S_CIRCULAR });
31 expect(deepCopy(new Date(0))).toEqual(new Date(0));
32 expect(deepCopy({ a: 1, b: 2 })).toEqual({ a: 1, b: 2 });
33 expect(deepCopy({ o: { a: [{ b: 1 }] } })).toEqual({ o: { a: [{ b: 1 }] } });
34 expect(deepCopy(Symbol.for("a"))).toEqual(Symbol.for("a"));
35 expect(deepCopy(document.createElement("div"))).toEqual(document.createElement("div"));
36 expect(deepCopy([1, 2, 3])).toEqual([1, 2, 3]);
37 });
38
39 test("deepEqual", () => {
40 const TRUTHY_CASES = [
41 [true, true],
42 [false, false],
43 [null, null],
44 [recursive, recursive],
45 [new Date(0), new Date(0)],
46 [
47 { b: 2, a: 1 },
48 { a: 1, b: 2 },
49 ],
50 [{ o: { a: [{ b: 1 }] } }, { o: { a: [{ b: 1 }] } }],
51 [Symbol.for("a"), Symbol.for("a")],
52 [document.createElement("div"), document.createElement("div")],
53 [
54 [1, 2, 3],
55 [1, 2, 3],
56 ],
57 ];
58 const FALSY_CASES = [
59 [true, false],
60 [null, undefined],
61 [recursive, { ...recursive, a: 1 }],
62 [
63 [1, 2, 3],
64 [3, 1, 2],
65 ],
66 [new Date(0), new Date(1_000)],
67 [{ a: new Date(0) }, { a: 0 }],
68 [document.createElement("a"), document.createElement("div")],
69 [{ [Symbol("a")]: 1 }, { [Symbol("a")]: 1 }],
70 ];
71 const TRUTHY_IF_UNORDERED_CASES = [
72 [
73 [1, "2", 3],
74 ["2", 3, 1],
75 ],
76 [
77 [1, { a: [4, 2] }, "3"],
78 [{ a: [2, 4] }, "3", 1],
79 ],
80 [
81 new Set([
82 "abc",
83 new Map([
84 ["b", 2],
85 ["a", 1],
86 ]),
87 ]),
88 new Set([
89 new Map([
90 ["a", 1],
91 ["b", 2],
92 ]),
93 "abc",
94 ]),
95 ],
96 ];
97
98 expect.assertions(
99 TRUTHY_CASES.length + FALSY_CASES.length + TRUTHY_IF_UNORDERED_CASES.length * 2
100 );
101
102 for (const [a, b] of TRUTHY_CASES) {
103 expect(deepEqual(a, b)).toBe(true, {
104 message: [a, `==`, b],
105 });
106 }
107 for (const [a, b] of FALSY_CASES) {
108 expect(deepEqual(a, b)).toBe(false, {
109 message: [a, `!=`, b],
110 });
111 }
112 for (const [a, b] of TRUTHY_IF_UNORDERED_CASES) {
113 expect(deepEqual(a, b)).toBe(false, {
114 message: [a, `!=`, b],
115 });
116 expect(deepEqual(a, b, { ignoreOrder: true })).toBe(true, {
117 message: [a, `==`, b, `(unordered))`],
118 });
119 }
120 });
121
122 test("formatHumanReadable", () => {
123 // Strings
124 expect(formatHumanReadable("abc")).toBe(`"abc"`);
125 expect(formatHumanReadable("a".repeat(300))).toBe(`"${"a".repeat(80)}…"`);
126 expect(formatHumanReadable(`with "double quotes"`)).toBe(`'with "double quotes"'`);
127 expect(formatHumanReadable(`with "double quotes" and 'single quote'`)).toBe(
128 `\`with "double quotes" and 'single quote'\``
129 );
130 // Numbers
131 expect(formatHumanReadable(1)).toBe(`1`);
132 // Other primitives
133 expect(formatHumanReadable(true)).toBe(`true`);
134 expect(formatHumanReadable(null)).toBe(`null`);
135 // Functions & classes
136 expect(formatHumanReadable(async function oui() {})).toBe(`async function oui() { … }`);
137 expect(formatHumanReadable(class Oui {})).toBe(`class Oui { … }`);
138 // Iterators
139 expect(formatHumanReadable([1, 2, 3])).toBe(`[1, 2, 3]`);
140 expect(formatHumanReadable(new Set([1, 2, 3]))).toBe(`Set [1, 2, 3]`);
141 expect(
142 formatHumanReadable(
143 new Map([
144 ["a", 1],
145 ["b", 2],
146 ])
147 )
148 ).toBe(`Map [["a", 1], ["b", 2]]`);
149 // Objects
150 expect(formatHumanReadable(/ab(c)d/gi)).toBe(`/ab(c)d/gi`);
151 expect(formatHumanReadable(new Date("1997-01-09T12:30:00.000Z"))).toBe(
152 `1997-01-09T12:30:00.000Z`
153 );
154 expect(formatHumanReadable({})).toBe(`{ }`);
155 expect(formatHumanReadable({ a: { b: 1 } })).toBe(`{ a: { b: 1 } }`);
156 expect(
157 formatHumanReadable(
158 new Proxy(
159 {
160 allowed: true,
161 get forbidden() {
162 throw new Error("Cannot access!");
163 },
164 },
165 {}
166 )
167 )
168 ).toBe(`{ allowed: true }`);
169 expect(formatHumanReadable(window)).toBe(`Window { }`);
170 // Nodes
171 expect(formatHumanReadable(document.createElement("div"))).toBe("<div>");
172 expect(formatHumanReadable(document.createTextNode("some text"))).toBe("#text");
173 expect(formatHumanReadable(document)).toBe("#document");
174 });
175
176 test("formatTechnical", () => {
177 expect(
178 formatTechnical({
179 b: 2,
180 [Symbol("s")]: "value",
181 a: true,
182 })
183 ).toBe(
184 `{
185 a: true,
186 b: 2,
187 Symbol(s): "value",
188 }`.trim()
189 );
190
191 expect(formatTechnical(["a", "b"])).toBe(
192 `[
193 "a",
194 "b",
195 ]`.trim()
196 );
197
198 class List extends Array {}
199
200 expect(formatTechnical(new List("a", "b"))).toBe(
201 `List [
202 "a",
203 "b",
204 ]`.trim()
205 );
206
207 function toArguments() {
208 return arguments;
209 }
210
211 expect(formatTechnical(toArguments("a", "b"))).toBe(
212 `Arguments [
213 "a",
214 "b",
215 ]`.trim()
216 );
217 });
218
219 test("generateHash", () => {
220 expect(generateHash("abc")).toHaveLength(8);
221 expect(generateHash("abcdef")).toHaveLength(8);
222 expect(generateHash("abc")).toBe(generateHash("abc"));
223
224 expect(generateHash("abc")).not.toBe(generateHash("def"));
225 });
226
227 test("isInstanceOf", async () => {
228 await mountForTest(/* xml */ `
229 <iframe srcdoc="" />
230 `);
231
232 expect(() => isInstanceOf()).toThrow(TypeError);
233 expect(() => isInstanceOf("a")).toThrow(TypeError);
234
235 expect(isInstanceOf(null, null)).toBe(false);
236 expect(isInstanceOf(undefined, undefined)).toBe(false);
237 expect(isInstanceOf("", String)).toBe(false);
238 expect(isInstanceOf(24, Number)).toBe(false);
239 expect(isInstanceOf(true, Boolean)).toBe(false);
240
241 class List extends Array {}
242
243 class A {}
244 class B extends A {}
245
246 expect(isInstanceOf([], Array)).toBe(true);
247 expect(isInstanceOf(new List(), Array)).toBe(true);
248 expect(isInstanceOf(new B(), B)).toBe(true);
249 expect(isInstanceOf(new B(), A)).toBe(true);
250 expect(isInstanceOf(new Error("error"), Error)).toBe(true);
251 expect(isInstanceOf(/a/, RegExp, Date)).toBe(true);
252 expect(isInstanceOf(new Date(), RegExp, Date)).toBe(true);
253
254 const { contentDocument, contentWindow } = queryOne("iframe");
255
256 expect(isInstanceOf(queryOne("iframe"), HTMLIFrameElement)).toBe(true);
257 expect(contentWindow instanceof Window).toBe(false);
258 expect(isInstanceOf(contentWindow, Window)).toBe(true);
259 expect(contentDocument.body instanceof HTMLBodyElement).toBe(false);
260 expect(isInstanceOf(contentDocument.body, HTMLBodyElement)).toBe(true);
261 });
262
263 test("isIterable", () => {
264 expect(isIterable([1, 2, 3])).toBe(true);
265 expect(isIterable(new Set([1, 2, 3]))).toBe(true);
266
267 expect(isIterable(null)).toBe(false);
268 expect(isIterable("abc")).toBe(false);
269 expect(isIterable({})).toBe(false);
270 });
271
272 test("levenshtein", () => {
273 expect(levenshtein("abc", "abc")).toBe(0);
274 expect(levenshtein("abc", "àbc ")).toBe(2);
275 expect(levenshtein("abc", "def")).toBe(3);
276 expect(levenshtein("abc", "adc")).toBe(1);
277 });
278
279 test("parseQuery & lookup", () => {
280 /**
281 * @param {string} query
282 * @param {string[]} itemsList
283 * @param {string} [property]
284 */
285 const expectQuery = (query, itemsList, property = "key") => {
286 const keyedItems = itemsList.map((item) => ({ [property]: item }));
287 const result = lookup(parseQuery(query), keyedItems);
288 return {
289 /**
290 * @param {string[]} expected
291 */
292 toEqual: (expected) =>
293 expect(result).toEqual(
294 expected.map((item) => ({ [property]: item })),
295 { message: `query ${query} should match ${expected}` }
296 ),
297 };
298 };
299
300 const list = [
301 "Frodo",
302 "Sam",
303 "Merry",
304 "Pippin",
305 "Frodo Sam",
306 "Merry Pippin",
307 "Frodo Sam Merry Pippin",
308 ];
309
310 // Error handling
311 expect(() => parseQuery()).toThrow();
312 expect(() => lookup()).toThrow();
313 expect(() => lookup("a", [{ key: "a" }])).toThrow();
314 expect(() => lookup(parseQuery("a"))).toThrow();
315
316 // Empty query and/or empty lists
317 expectQuery("", []).toEqual([]);
318 expectQuery("", ["bababa", "baaab", "cccbccb"]).toEqual(["bababa", "baaab", "cccbccb"]);
319 expectQuery("aaa", []).toEqual([]);
320
321 // Regex
322 expectQuery(`/.b$/`, ["bababa", "baaab", "cccbccB"]).toEqual(["baaab"]);
323 expectQuery(`/.b$/i`, ["bababa", "baaab", "cccbccB"]).toEqual(["baaab", "cccbccB"]);
324
325 // Exact match
326 expectQuery(`"aaa"`, ["bababa", "baaab", "cccbccb"]).toEqual(["baaab"]);
327 expectQuery(`"sam"`, list).toEqual([]);
328 expectQuery(`"Sam"`, list).toEqual(["Sam", "Frodo Sam", "Frodo Sam Merry Pippin"]);
329 expectQuery(`"Sam" "Frodo"`, list).toEqual(["Frodo Sam", "Frodo Sam Merry Pippin"]);
330 expectQuery(`"Frodo Sam"`, list).toEqual(["Frodo Sam", "Frodo Sam Merry Pippin"]);
331 expectQuery(`"FrodoSam"`, list).toEqual([]);
332 expectQuery(`"Frodo Sam"`, list).toEqual([]);
333 expectQuery(`"Sam" -"Frodo"`, list).toEqual(["Sam"]);
334
335 // Partial (fuzzy) match
336 expectQuery(`aaa`, ["bababa", "baaab", "cccbccb"]).toEqual(["baaab", "bababa"]);
337 expectQuery(`aaa -bbb`, ["bababa", "baaab", "cccbccb"]).toEqual(["baaab"]);
338 expectQuery(`-aaa`, ["bababa", "baaab", "cccbccb"]).toEqual(["cccbccb"]);
339 expectQuery(`frosapip`, list).toEqual(["Frodo Sam Merry Pippin"]);
340 expectQuery(`-s fro`, list).toEqual(["Frodo"]);
341 expectQuery(` FR SAPI `, list).toEqual(["Frodo Sam Merry Pippin"]);
342
343 // Mixed queries
344 expectQuery(`"Sam" fro pip`, list).toEqual(["Frodo Sam Merry Pippin"]);
345 expectQuery(`fro"Sam"pip`, list).toEqual(["Frodo Sam Merry Pippin"]);
346 expectQuery(`-"Frodo" s`, list).toEqual(["Sam"]);
347 expectQuery(`"Merry" -p`, list).toEqual(["Merry"]);
348 expectQuery(`"rry" -s`, list).toEqual(["Merry", "Merry Pippin"]);
349 });
350
351 test("match", () => {
352 expect(match("abc", /^abcd?/)).toBe(true);
353 expect(match(new Error("error message"), "message")).toBe(true);
354 });
355
356 test("title", () => {
357 expect(title("abcDef")).toBe("AbcDef");
358 });
359
360 test("toExplicitString", () => {
361 expect(toExplicitString("\n")).toBe(`\\n`);
362 expect(toExplicitString("\t")).toBe(`\\t`);
363
364 expect(toExplicitString(" \n")).toBe(` \n`);
365 expect(toExplicitString("\t ")).toBe(`\t `);
366
367 expect(toExplicitString("Abc\u200BDef")).toBe(`Abc\\u200bDef`);
368 });
369 });