Path: blob/master/src/packages/conat/core/patterns.test.ts
1453 views
/*1DEVELOPMENT:23pnpm test ./patterns.test.ts4*/56import { Patterns } from "./patterns";7import { randomId } from "@cocalc/conat/names";89function expectEqual(actual: any[], expected: any[]) {10expect(actual).toEqual(expect.arrayContaining(expected));11expect(actual).toHaveLength(expected.length);12}1314describe("test some basic pattern matching", () => {15it("tests some simple examples with just one or no matches", () => {16const p = new Patterns();17p.set("x", 0);18p.set("a.b.>", 0);19p.set("a.*", 0);20expectEqual(p.matches("x"), ["x"]);21expectEqual(p.matches("y"), []);22expectEqual(p.matches("a.b.c"), ["a.b.>"]);23expectEqual(p.matches("a.b"), ["a.*"]);24});2526it("some examples with several matches", () => {27const p = new Patterns();28p.set("a.b.>", 0);29p.set("a.*.*", 0);30expectEqual(p.matches("a.b.c"), ["a.b.>", "a.*.*"]);31expectEqual(p.matches("a.b.c.d"), ["a.b.>"]);32});3334it("example where we delete a pattern", () => {35const p = new Patterns();36p.set("a.b.>", 0);37p.set("a.b.c", 0);38p.set("a.b.d", 0);39expectEqual(p.matches("a.b.c"), ["a.b.>", "a.b.c"]);40expectEqual(p.matches("a.b.d"), ["a.b.>", "a.b.d"]);41expectEqual(p.matches("a.b.c.d"), ["a.b.>"]);42p.delete("a.b.c");43expectEqual(p.matches("a.b.d"), ["a.b.>", "a.b.d"]);44expectEqual(p.matches("a.b.c"), ["a.b.>"]);45p.delete("a.b.d");46expectEqual(p.matches("a.b.d"), ["a.b.>"]);47p.delete("a.b.>");48expectEqual(p.matches("a.b.d"), []);49});50});5152describe("do some stress tests", () => {53const patterns = 1e5;5455let p;56const knownIds: string[] = [];57it(`create ${patterns} patterns`, () => {58p = new Patterns();59for (const seg1 of ["service", "hub", "project", "account", "global"]) {60for (const seg2 of ["*", "x"]) {61for (let i = 0; i < patterns / 10; i++) {62const id = randomId();63knownIds.push(id);64const pattern = `${seg1}.${seg2}.${id}`;65p.set(pattern, 0);66}67}68}69});7071const count = 1e6;72let m = 0;73it(`match ${count} times against them`, () => {74for (const seg1 of ["service", "hub", "project", "account", "global"]) {75for (const seg2 of ["a", "x"]) {76for (let i = 0; i < count / 10; i++) {77const subject = `${seg1}.${seg2}.${knownIds[i] ?? randomId()}`;78m = Math.max(p.matches(subject).length, m);79}80}81}82expect(m).toBeGreaterThan(0);83});84});858687