test: tighten safe regex assertions

This commit is contained in:
Shakker
2026-05-08 21:05:06 +01:00
parent c895afe872
commit 986efee29c

View File

@@ -6,6 +6,15 @@ import {
testRegexWithBoundedInput,
} from "./safe-regex.js";
function expectCompiledRegex(pattern: string, flags?: string): RegExp {
const re = compileSafeRegex(pattern, flags);
expect(re).toBeInstanceOf(RegExp);
if (!re) {
throw new Error(`Expected ${pattern} to compile safely`);
}
return re;
}
describe("safe regex", () => {
it.each([
["(a+)+$", true],
@@ -30,16 +39,14 @@ describe("safe regex", () => {
});
it("compiles common safe filter regex", () => {
const re = compileSafeRegex("^agent:.*:discord:");
expect(re).toBeInstanceOf(RegExp);
expect(re?.test("agent:main:discord:channel:123")).toBe(true);
expect(re?.test("agent:main:telegram:channel:123")).toBe(false);
const re = expectCompiledRegex("^agent:.*:discord:");
expect(re.test("agent:main:discord:channel:123")).toBe(true);
expect(re.test("agent:main:telegram:channel:123")).toBe(false);
});
it("supports explicit flags", () => {
const re = compileSafeRegex("token=([A-Za-z0-9]+)", "gi");
expect(re).toBeInstanceOf(RegExp);
expect("TOKEN=abcd1234".replace(re as RegExp, "***")).toBe("***");
const re = expectCompiledRegex("token=([A-Za-z0-9]+)", "gi");
expect("TOKEN=abcd1234".replace(re, "***")).toBe("***");
});
it.each([