Skip to content

Commit a28a44f

Browse files
test: 添加 FileEditTool/permissions/filterToolsByDenyRules 测试
- FileEditTool/utils.test.ts: 24 tests (normalizeQuotes, stripTrailingWhitespace, findActualString, preserveQuoteStyle, applyEditToFile) - permissions/permissions.test.ts: 13 tests (getDenyRuleForTool, getAskRuleForTool, getDenyRuleForAgent, filterDeniedAgents) - tools.test.ts: 扩展 5 tests (filterToolsByDenyRules 过滤逻辑) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 43af260 commit a28a44f

3 files changed

Lines changed: 388 additions & 1 deletion

File tree

src/__tests__/tools.test.ts

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, test } from "bun:test";
2-
import { parseToolPreset } from "../tools";
2+
import { parseToolPreset, filterToolsByDenyRules } from "../tools";
3+
import { getEmptyToolPermissionContext } from "../Tool";
34

45
describe("parseToolPreset", () => {
56
test('returns "default" for "default" input', () => {
@@ -22,3 +23,60 @@ describe("parseToolPreset", () => {
2223
expect(parseToolPreset("custom-preset")).toBeNull();
2324
});
2425
});
26+
27+
// ─── filterToolsByDenyRules ─────────────────────────────────────────────
28+
29+
describe("filterToolsByDenyRules", () => {
30+
const mockTools = [
31+
{ name: "Bash", mcpInfo: undefined },
32+
{ name: "Read", mcpInfo: undefined },
33+
{ name: "Write", mcpInfo: undefined },
34+
{ name: "mcp__server__tool", mcpInfo: { serverName: "server", toolName: "tool" } },
35+
];
36+
37+
test("returns all tools when no deny rules", () => {
38+
const ctx = getEmptyToolPermissionContext();
39+
const result = filterToolsByDenyRules(mockTools, ctx);
40+
expect(result).toHaveLength(4);
41+
});
42+
43+
test("filters out denied tool by name", () => {
44+
const ctx = {
45+
...getEmptyToolPermissionContext(),
46+
alwaysDenyRules: {
47+
localSettings: ["Bash"],
48+
},
49+
};
50+
const result = filterToolsByDenyRules(mockTools, ctx as any);
51+
expect(result.find((t) => t.name === "Bash")).toBeUndefined();
52+
expect(result).toHaveLength(3);
53+
});
54+
55+
test("filters out multiple denied tools", () => {
56+
const ctx = {
57+
...getEmptyToolPermissionContext(),
58+
alwaysDenyRules: {
59+
localSettings: ["Bash", "Write"],
60+
},
61+
};
62+
const result = filterToolsByDenyRules(mockTools, ctx as any);
63+
expect(result).toHaveLength(2);
64+
expect(result.map((t) => t.name)).toEqual(["Read", "mcp__server__tool"]);
65+
});
66+
67+
test("returns empty array when all tools denied", () => {
68+
const ctx = {
69+
...getEmptyToolPermissionContext(),
70+
alwaysDenyRules: {
71+
localSettings: mockTools.map((t) => t.name),
72+
},
73+
};
74+
const result = filterToolsByDenyRules(mockTools, ctx as any);
75+
expect(result).toHaveLength(0);
76+
});
77+
78+
test("handles empty tools array", () => {
79+
const ctx = getEmptyToolPermissionContext();
80+
expect(filterToolsByDenyRules([], ctx)).toEqual([]);
81+
});
82+
});
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
import { mock, describe, expect, test } from "bun:test";
2+
3+
// Mock log.ts to cut the heavy dependency chain
4+
mock.module("src/utils/log.ts", () => ({
5+
logError: () => {},
6+
logToFile: () => {},
7+
getLogDisplayTitle: () => "",
8+
logEvent: () => {},
9+
logMCPError: () => {},
10+
logMCPDebug: () => {},
11+
dateToFilename: (d: Date) => d.toISOString().replace(/[:.]/g, "-"),
12+
getLogFilePath: () => "/tmp/mock-log",
13+
attachErrorLogSink: () => {},
14+
getInMemoryErrors: () => [],
15+
loadErrorLogs: async () => [],
16+
getErrorLogByIndex: async () => null,
17+
captureAPIRequest: () => {},
18+
_resetErrorLogForTesting: () => {},
19+
}));
20+
21+
const {
22+
normalizeQuotes,
23+
stripTrailingWhitespace,
24+
findActualString,
25+
preserveQuoteStyle,
26+
applyEditToFile,
27+
LEFT_SINGLE_CURLY_QUOTE,
28+
RIGHT_SINGLE_CURLY_QUOTE,
29+
LEFT_DOUBLE_CURLY_QUOTE,
30+
RIGHT_DOUBLE_CURLY_QUOTE,
31+
} = await import("../utils");
32+
33+
// ─── normalizeQuotes ────────────────────────────────────────────────────
34+
35+
describe("normalizeQuotes", () => {
36+
test("converts left single curly to straight", () => {
37+
expect(normalizeQuotes(`${LEFT_SINGLE_CURLY_QUOTE}hello`)).toBe("'hello");
38+
});
39+
40+
test("converts right single curly to straight", () => {
41+
expect(normalizeQuotes(`hello${RIGHT_SINGLE_CURLY_QUOTE}`)).toBe("hello'");
42+
});
43+
44+
test("converts left double curly to straight", () => {
45+
expect(normalizeQuotes(`${LEFT_DOUBLE_CURLY_QUOTE}hello`)).toBe('"hello');
46+
});
47+
48+
test("converts right double curly to straight", () => {
49+
expect(normalizeQuotes(`hello${RIGHT_DOUBLE_CURLY_QUOTE}`)).toBe('hello"');
50+
});
51+
52+
test("leaves straight quotes unchanged", () => {
53+
expect(normalizeQuotes("'hello' \"world\"")).toBe("'hello' \"world\"");
54+
});
55+
56+
test("handles empty string", () => {
57+
expect(normalizeQuotes("")).toBe("");
58+
});
59+
});
60+
61+
// ─── stripTrailingWhitespace ────────────────────────────────────────────
62+
63+
describe("stripTrailingWhitespace", () => {
64+
test("strips trailing spaces from lines", () => {
65+
expect(stripTrailingWhitespace("hello \nworld ")).toBe("hello\nworld");
66+
});
67+
68+
test("strips trailing tabs", () => {
69+
expect(stripTrailingWhitespace("hello\t\nworld\t")).toBe("hello\nworld");
70+
});
71+
72+
test("preserves leading whitespace", () => {
73+
expect(stripTrailingWhitespace(" hello \n world ")).toBe(
74+
" hello\n world"
75+
);
76+
});
77+
78+
test("handles empty string", () => {
79+
expect(stripTrailingWhitespace("")).toBe("");
80+
});
81+
82+
test("handles CRLF line endings", () => {
83+
expect(stripTrailingWhitespace("hello \r\nworld ")).toBe(
84+
"hello\r\nworld"
85+
);
86+
});
87+
88+
test("handles no trailing whitespace", () => {
89+
expect(stripTrailingWhitespace("hello\nworld")).toBe("hello\nworld");
90+
});
91+
});
92+
93+
// ─── findActualString ───────────────────────────────────────────────────
94+
95+
describe("findActualString", () => {
96+
test("finds exact match", () => {
97+
expect(findActualString("hello world", "hello")).toBe("hello");
98+
});
99+
100+
test("finds match with curly quotes normalized", () => {
101+
const fileContent = `${LEFT_DOUBLE_CURLY_QUOTE}hello${RIGHT_DOUBLE_CURLY_QUOTE}`;
102+
const result = findActualString(fileContent, '"hello"');
103+
expect(result).not.toBeNull();
104+
});
105+
106+
test("returns null when not found", () => {
107+
expect(findActualString("hello world", "xyz")).toBeNull();
108+
});
109+
110+
test("returns null for empty search in non-empty content", () => {
111+
// Empty string is always found at index 0 via includes()
112+
const result = findActualString("hello", "");
113+
expect(result).toBe("");
114+
});
115+
});
116+
117+
// ─── preserveQuoteStyle ─────────────────────────────────────────────────
118+
119+
describe("preserveQuoteStyle", () => {
120+
test("returns newString unchanged when no normalization happened", () => {
121+
expect(preserveQuoteStyle("hello", "hello", "world")).toBe("world");
122+
});
123+
124+
test("converts straight double quotes to curly in replacement", () => {
125+
const oldString = '"hello"';
126+
const actualOldString = `${LEFT_DOUBLE_CURLY_QUOTE}hello${RIGHT_DOUBLE_CURLY_QUOTE}`;
127+
const newString = '"world"';
128+
const result = preserveQuoteStyle(oldString, actualOldString, newString);
129+
expect(result).toContain(LEFT_DOUBLE_CURLY_QUOTE);
130+
expect(result).toContain(RIGHT_DOUBLE_CURLY_QUOTE);
131+
});
132+
});
133+
134+
// ─── applyEditToFile ────────────────────────────────────────────────────
135+
136+
describe("applyEditToFile", () => {
137+
test("replaces first occurrence by default", () => {
138+
expect(applyEditToFile("foo bar foo", "foo", "baz")).toBe("baz bar foo");
139+
});
140+
141+
test("replaces all occurrences with replaceAll=true", () => {
142+
expect(applyEditToFile("foo bar foo", "foo", "baz", true)).toBe(
143+
"baz bar baz"
144+
);
145+
});
146+
147+
test("handles deletion (empty newString) with trailing newline", () => {
148+
const result = applyEditToFile("line1\nline2\nline3\n", "line2", "");
149+
expect(result).toBe("line1\nline3\n");
150+
});
151+
152+
test("handles deletion without trailing newline", () => {
153+
const result = applyEditToFile("foobar", "foo", "");
154+
expect(result).toBe("bar");
155+
});
156+
157+
test("handles no match (returns original)", () => {
158+
expect(applyEditToFile("hello world", "xyz", "abc")).toBe("hello world");
159+
});
160+
161+
test("handles empty original content with insertion", () => {
162+
expect(applyEditToFile("", "", "new content")).toBe("new content");
163+
});
164+
});
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
import { mock, describe, expect, test } from "bun:test";
2+
3+
// Mock log.ts to cut the heavy dependency chain
4+
mock.module("src/utils/log.ts", () => ({
5+
logError: () => {},
6+
logToFile: () => {},
7+
getLogDisplayTitle: () => "",
8+
logEvent: () => {},
9+
logMCPError: () => {},
10+
logMCPDebug: () => {},
11+
dateToFilename: (d: Date) => d.toISOString().replace(/[:.]/g, "-"),
12+
getLogFilePath: () => "/tmp/mock-log",
13+
attachErrorLogSink: () => {},
14+
getInMemoryErrors: () => [],
15+
loadErrorLogs: async () => [],
16+
getErrorLogByIndex: async () => null,
17+
captureAPIRequest: () => {},
18+
_resetErrorLogForTesting: () => {},
19+
}));
20+
21+
// Mock slowOperations to avoid bun:bundle
22+
mock.module("src/utils/slowOperations.ts", () => ({
23+
jsonStringify: JSON.stringify,
24+
jsonParse: JSON.parse,
25+
slowLogging: { enabled: false },
26+
clone: (v: any) => structuredClone(v),
27+
cloneDeep: (v: any) => structuredClone(v),
28+
callerFrame: () => "",
29+
SLOW_OPERATION_THRESHOLD_MS: 100,
30+
writeFileSync_DEPRECATED: () => {},
31+
}));
32+
33+
const {
34+
getDenyRuleForTool,
35+
getAskRuleForTool,
36+
getDenyRuleForAgent,
37+
filterDeniedAgents,
38+
} = await import("../permissions");
39+
40+
import { getEmptyToolPermissionContext } from "../../../Tool";
41+
42+
// ─── Helper ─────────────────────────────────────────────────────────────
43+
44+
function makeContext(opts: {
45+
denyRules?: string[];
46+
askRules?: string[];
47+
}) {
48+
const ctx = getEmptyToolPermissionContext();
49+
const deny: Record<string, string[]> = {};
50+
const ask: Record<string, string[]> = {};
51+
52+
// alwaysDenyRules stores raw rule strings — getDenyRules() calls
53+
// permissionRuleValueFromString internally
54+
if (opts.denyRules?.length) {
55+
deny["localSettings"] = opts.denyRules;
56+
}
57+
if (opts.askRules?.length) {
58+
ask["localSettings"] = opts.askRules;
59+
}
60+
61+
return {
62+
...ctx,
63+
alwaysDenyRules: deny,
64+
alwaysAskRules: ask,
65+
} as any;
66+
}
67+
68+
function makeTool(name: string, mcpInfo?: { serverName: string; toolName: string }) {
69+
return { name, mcpInfo };
70+
}
71+
72+
// ─── getDenyRuleForTool ─────────────────────────────────────────────────
73+
74+
describe("getDenyRuleForTool", () => {
75+
test("returns null when no deny rules", () => {
76+
const ctx = makeContext({});
77+
expect(getDenyRuleForTool(ctx, makeTool("Bash"))).toBeNull();
78+
});
79+
80+
test("returns matching deny rule for tool", () => {
81+
const ctx = makeContext({ denyRules: ["Bash"] });
82+
const result = getDenyRuleForTool(ctx, makeTool("Bash"));
83+
expect(result).not.toBeNull();
84+
expect(result!.ruleValue.toolName).toBe("Bash");
85+
});
86+
87+
test("returns null for non-matching tool", () => {
88+
const ctx = makeContext({ denyRules: ["Bash"] });
89+
expect(getDenyRuleForTool(ctx, makeTool("Read"))).toBeNull();
90+
});
91+
92+
test("rule with content does not match whole-tool deny", () => {
93+
// getDenyRuleForTool uses toolMatchesRule which requires ruleContent === undefined
94+
// Rules like "Bash(rm -rf)" only match specific invocations, not the entire tool
95+
const ctx = makeContext({ denyRules: ["Bash(rm -rf)"] });
96+
const result = getDenyRuleForTool(ctx, makeTool("Bash"));
97+
expect(result).toBeNull();
98+
});
99+
});
100+
101+
// ─── getAskRuleForTool ──────────────────────────────────────────────────
102+
103+
describe("getAskRuleForTool", () => {
104+
test("returns null when no ask rules", () => {
105+
const ctx = makeContext({});
106+
expect(getAskRuleForTool(ctx, makeTool("Bash"))).toBeNull();
107+
});
108+
109+
test("returns matching ask rule", () => {
110+
const ctx = makeContext({ askRules: ["Write"] });
111+
const result = getAskRuleForTool(ctx, makeTool("Write"));
112+
expect(result).not.toBeNull();
113+
});
114+
115+
test("returns null for non-matching tool", () => {
116+
const ctx = makeContext({ askRules: ["Write"] });
117+
expect(getAskRuleForTool(ctx, makeTool("Bash"))).toBeNull();
118+
});
119+
});
120+
121+
// ─── getDenyRuleForAgent ────────────────────────────────────────────────
122+
123+
describe("getDenyRuleForAgent", () => {
124+
test("returns null when no deny rules", () => {
125+
const ctx = makeContext({});
126+
expect(getDenyRuleForAgent(ctx, "Agent", "Explore")).toBeNull();
127+
});
128+
129+
test("returns matching deny rule for agent type", () => {
130+
const ctx = makeContext({ denyRules: ["Agent(Explore)"] });
131+
const result = getDenyRuleForAgent(ctx, "Agent", "Explore");
132+
expect(result).not.toBeNull();
133+
});
134+
135+
test("returns null for non-matching agent type", () => {
136+
const ctx = makeContext({ denyRules: ["Agent(Explore)"] });
137+
expect(getDenyRuleForAgent(ctx, "Agent", "Research")).toBeNull();
138+
});
139+
});
140+
141+
// ─── filterDeniedAgents ─────────────────────────────────────────────────
142+
143+
describe("filterDeniedAgents", () => {
144+
test("returns all agents when no deny rules", () => {
145+
const ctx = makeContext({});
146+
const agents = [{ agentType: "Explore" }, { agentType: "Research" }];
147+
expect(filterDeniedAgents(agents, ctx, "Agent")).toEqual(agents);
148+
});
149+
150+
test("filters out denied agent type", () => {
151+
const ctx = makeContext({ denyRules: ["Agent(Explore)"] });
152+
const agents = [{ agentType: "Explore" }, { agentType: "Research" }];
153+
const result = filterDeniedAgents(agents, ctx, "Agent");
154+
expect(result).toHaveLength(1);
155+
expect(result[0]!.agentType).toBe("Research");
156+
});
157+
158+
test("returns empty array when all agents denied", () => {
159+
const ctx = makeContext({
160+
denyRules: ["Agent(Explore)", "Agent(Research)"],
161+
});
162+
const agents = [{ agentType: "Explore" }, { agentType: "Research" }];
163+
expect(filterDeniedAgents(agents, ctx, "Agent")).toEqual([]);
164+
});
165+
});

0 commit comments

Comments
 (0)