This repository was archived by the owner on May 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathexecuteCommandTool.spec.ts
More file actions
306 lines (264 loc) · 10.7 KB
/
Copy pathexecuteCommandTool.spec.ts
File metadata and controls
306 lines (264 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// npx vitest run src/core/tools/__tests__/executeCommandTool.spec.ts
import type { ToolUsage } from "@roo-code/types"
import * as vscode from "vscode"
import { Task } from "../../task/Task"
import { formatResponse } from "../../prompts/responses"
import { ToolUse, AskApproval, HandleError, PushToolResult } from "../../../shared/tools"
import { unescapeHtmlEntities } from "../../../utils/text-normalization"
// Mock dependencies
vitest.mock("execa", () => ({
execa: vitest.fn(),
}))
vitest.mock("fs/promises", () => ({
default: {
access: vitest.fn().mockResolvedValue(undefined),
},
}))
vitest.mock("vscode", () => ({
workspace: {
getConfiguration: vitest.fn(),
},
}))
vitest.mock("../../../integrations/terminal/TerminalRegistry", () => ({
TerminalRegistry: {
getOrCreateTerminal: vitest.fn().mockResolvedValue({
runCommand: vitest.fn().mockResolvedValue(undefined),
getCurrentWorkingDirectory: vitest.fn().mockReturnValue("/test/workspace"),
}),
},
}))
vitest.mock("../../task/Task")
vitest.mock("../../prompts/responses")
// Import the module
import * as executeCommandModule from "../ExecuteCommandTool"
const { executeCommandTool } = executeCommandModule
describe("executeCommandTool", () => {
// Setup common test variables
let mockCline: any & { consecutiveMistakeCount: number; didRejectTool: boolean }
let mockAskApproval: any
let mockHandleError: any
let mockPushToolResult: any
let mockToolUse: ToolUse<"execute_command">
beforeEach(() => {
// Reset mocks
vitest.clearAllMocks()
// Spy on executeCommandInTerminal and mock its return value
vitest.spyOn(executeCommandModule, "executeCommandInTerminal").mockResolvedValue([false, "Command executed"])
// Create mock implementations with eslint directives to handle the type issues
mockCline = {
ask: vitest.fn().mockResolvedValue(undefined),
say: vitest.fn().mockResolvedValue(undefined),
sayAndCreateMissingParamError: vitest.fn().mockResolvedValue("Missing parameter error"),
consecutiveMistakeCount: 0,
didRejectTool: false,
rooIgnoreController: {
validateCommand: vitest.fn().mockReturnValue(null),
},
recordToolUsage: vitest.fn().mockReturnValue({} as ToolUsage),
recordToolError: vitest.fn(),
processQueuedMessages: vitest.fn(),
providerRef: {
deref: vitest.fn().mockResolvedValue({
getState: vitest.fn().mockResolvedValue({
terminalOutputLineLimit: 500,
terminalOutputCharacterLimit: 100000,
terminalShellIntegrationDisabled: true,
}),
postMessageToWebview: vitest.fn(),
}),
},
lastMessageTs: Date.now(),
cwd: "/test/workspace",
}
mockAskApproval = vitest.fn().mockResolvedValue(true)
mockHandleError = vitest.fn().mockResolvedValue(undefined)
mockPushToolResult = vitest.fn()
// Setup vscode config mock
const mockConfig = {
get: vitest.fn().mockImplementation((key: string, defaultValue: any) => defaultValue),
}
;(vscode.workspace.getConfiguration as any).mockReturnValue(mockConfig)
// Create a mock tool use object
mockToolUse = {
type: "tool_use",
name: "execute_command",
params: {
command: "echo test",
},
nativeArgs: {
command: "echo test",
},
partial: false,
}
})
/**
* Tests for HTML entity unescaping in commands
* This verifies that HTML entities are properly converted to their actual characters
*/
describe("HTML entity unescaping", () => {
it("should unescape < to < character", () => {
const input = "echo <test>"
const expected = "echo <test>"
expect(unescapeHtmlEntities(input)).toBe(expected)
})
it("should unescape > to > character", () => {
const input = "echo test > output.txt"
const expected = "echo test > output.txt"
expect(unescapeHtmlEntities(input)).toBe(expected)
})
it("should unescape & to & character", () => {
const input = "echo foo && echo bar"
const expected = "echo foo && echo bar"
expect(unescapeHtmlEntities(input)).toBe(expected)
})
it("should handle multiple mixed HTML entities", () => {
const input = "grep -E 'pattern' <file.txt >output.txt 2>&1"
const expected = "grep -E 'pattern' <file.txt >output.txt 2>&1"
expect(unescapeHtmlEntities(input)).toBe(expected)
})
})
// Now we can run these tests
describe("Basic functionality", () => {
it("should execute a command normally", async () => {
// Setup
mockToolUse.params.command = "echo test"
mockToolUse.nativeArgs = { command: "echo test" }
// Execute using the class-based handle method
await executeCommandTool.handle(mockCline as unknown as Task, mockToolUse, {
askApproval: mockAskApproval as unknown as AskApproval,
handleError: mockHandleError as unknown as HandleError,
pushToolResult: mockPushToolResult as unknown as PushToolResult,
})
// Verify
expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test")
expect(mockPushToolResult).toHaveBeenCalled()
// The exact message depends on the terminal mock's behavior
const result = mockPushToolResult.mock.calls[0][0]
expect(result).toContain("Command")
})
it("should process queued messages after command execution", async () => {
// Setup
mockToolUse.params.command = "echo test"
mockToolUse.nativeArgs = { command: "echo test" }
// Execute
await executeCommandTool.handle(mockCline as unknown as Task, mockToolUse, {
askApproval: mockAskApproval as unknown as AskApproval,
handleError: mockHandleError as unknown as HandleError,
pushToolResult: mockPushToolResult as unknown as PushToolResult,
})
// Verify that processQueuedMessages was called after command execution
expect(mockCline.processQueuedMessages).toHaveBeenCalled()
})
it("should pass along custom working directory if provided", async () => {
// Setup
mockToolUse.params.command = "echo test"
mockToolUse.params.cwd = "/custom/path"
mockToolUse.nativeArgs = { command: "echo test", cwd: "/custom/path" }
// Execute
await executeCommandTool.handle(mockCline as unknown as Task, mockToolUse, {
askApproval: mockAskApproval as unknown as AskApproval,
handleError: mockHandleError as unknown as HandleError,
pushToolResult: mockPushToolResult as unknown as PushToolResult,
})
// Verify - confirm the command was approved and result was pushed
// The custom path handling is tested in integration tests
expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test")
expect(mockPushToolResult).toHaveBeenCalled()
const result = mockPushToolResult.mock.calls[0][0]
expect(result).toContain("/custom/path")
})
})
describe("Error handling", () => {
it("should handle missing command parameter", async () => {
// Setup
mockToolUse.params.command = undefined
// Native tool calls must still supply a value; simulate a missing value with an empty string.
mockToolUse.nativeArgs = { command: "" }
// Execute
await executeCommandTool.handle(mockCline as unknown as Task, mockToolUse, {
askApproval: mockAskApproval as unknown as AskApproval,
handleError: mockHandleError as unknown as HandleError,
pushToolResult: mockPushToolResult as unknown as PushToolResult,
})
// Verify
expect(mockCline.consecutiveMistakeCount).toBe(1)
expect(mockCline.sayAndCreateMissingParamError).toHaveBeenCalledWith("execute_command", "command")
expect(mockPushToolResult).toHaveBeenCalledWith("Missing parameter error")
expect(mockAskApproval).not.toHaveBeenCalled()
expect(executeCommandModule.executeCommandInTerminal).not.toHaveBeenCalled()
})
it("should handle command rejection", async () => {
// Setup
mockToolUse.params.command = "echo test"
mockAskApproval.mockResolvedValue(false)
mockToolUse.nativeArgs = { command: "echo test" }
// Execute
await executeCommandTool.handle(mockCline as unknown as Task, mockToolUse, {
askApproval: mockAskApproval as unknown as AskApproval,
handleError: mockHandleError as unknown as HandleError,
pushToolResult: mockPushToolResult as unknown as PushToolResult,
})
// Verify
expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test")
// executeCommandInTerminal should not be called since approval was denied
expect(mockPushToolResult).not.toHaveBeenCalled()
})
it("should handle rooignore validation failures", async () => {
// Setup
mockToolUse.params.command = "cat .env"
mockToolUse.nativeArgs = { command: "cat .env" }
// Override the validateCommand mock to return a filename
const validateCommandMock = vitest.fn().mockReturnValue(".env")
mockCline.rooIgnoreController = {
validateCommand: validateCommandMock,
}
const mockRooIgnoreError = "RooIgnore error"
;(formatResponse.rooIgnoreError as any).mockReturnValue(mockRooIgnoreError)
// Execute
await executeCommandTool.handle(mockCline as unknown as Task, mockToolUse, {
askApproval: mockAskApproval as unknown as AskApproval,
handleError: mockHandleError as unknown as HandleError,
pushToolResult: mockPushToolResult as unknown as PushToolResult,
})
// Verify
expect(validateCommandMock).toHaveBeenCalledWith("cat .env")
expect(mockCline.say).toHaveBeenCalledWith("rooignore_error", ".env")
expect(formatResponse.rooIgnoreError).toHaveBeenCalledWith(".env")
expect(mockPushToolResult).toHaveBeenCalledWith(mockRooIgnoreError)
expect(mockAskApproval).not.toHaveBeenCalled()
// executeCommandInTerminal should not be called since rooignore blocked it
})
})
describe("Command execution timeout configuration", () => {
it("should include timeout parameter in ExecuteCommandOptions", () => {
// This test verifies that the timeout configuration is properly typed
// The actual timeout logic is tested in integration tests
// Note: timeout is stored internally in milliseconds but configured in seconds
const timeoutSeconds = 15
const options = {
executionId: "test-id",
command: "echo test",
commandExecutionTimeout: timeoutSeconds * 1000, // Convert to milliseconds
}
// Verify the options object has the expected structure
expect(options.commandExecutionTimeout).toBe(15000)
expect(typeof options.commandExecutionTimeout).toBe("number")
})
it("should handle timeout parameter in function signature", () => {
// Test that the executeCommandInTerminal function accepts timeout parameter
// This is a compile-time check that the types are correct
const mockOptions = {
executionId: "test-id",
command: "echo test",
customCwd: undefined,
terminalShellIntegrationDisabled: false,
terminalOutputLineLimit: 500,
commandExecutionTimeout: 0,
}
// Verify all required properties exist
expect(mockOptions.executionId).toBeDefined()
expect(mockOptions.command).toBeDefined()
expect(mockOptions.commandExecutionTimeout).toBeDefined()
})
})
})