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