Elffuss BraidHub

kikocis/continue public

main · 6.4 KiBRawPermalink
1import fs from "fs/promises";
2import os from "os";
3import path from "path";
4
5import { execaNode, type Subprocess } from "execa";
6
7export interface CLITestContext {
8 cliPath: string;
9 testDir: string;
10 configPath?: string;
11 sessionPath?: string;
12}
13
14export interface CLIRunOptions {
15 args?: string[];
16 input?: string;
17 env?: Record<string, string>;
18 timeout?: number;
19 expectError?: boolean;
20}
21
22export interface CLIRunResult {
23 stdout: string;
24 stderr: string;
25 exitCode: number;
26 error?: Error;
27}
28
29/**
30 * Creates a test context with isolated test directory
31 */
32export async function createTestContext(): Promise<CLITestContext> {
33 // Use the wrapper script that invokes runCli(), not the raw bundle entry
34 const cliPath = path.resolve("dist/cn.js");
35 const testDir = await fs.mkdtemp(path.join(os.tmpdir(), "cn-test-"));
36
37 // Ensure the CLI file exists before returning the context
38 try {
39 await fs.access(cliPath);
40 } catch {
41 throw new Error(
42 `CLI wrapper not found at ${cliPath}. Please run 'npm run build' first.`,
43 );
44 }
45
46 return {
47 cliPath,
48 testDir,
49 };
50}
51
52/**
53 * Cleans up test context
54 */
55export async function cleanupTestContext(
56 context: CLITestContext,
57): Promise<void> {
58 try {
59 await fs.rm(context.testDir, { recursive: true, force: true });
60 } catch {
61 // Ignore cleanup errors
62 }
63}
64
65/**
66 * Runs the CLI with given options
67 */
68export async function runCLI(
69 context: CLITestContext,
70 options: CLIRunOptions = {},
71): Promise<CLIRunResult> {
72 const {
73 args = [],
74 input,
75 env = {},
76 timeout = 10000,
77 expectError = false,
78 } = options;
79
80 const execOptions = {
81 cwd: context.testDir,
82 env: {
83 ...process.env,
84 CONTINUE_CLI_TEST: "true",
85 HOME: context.testDir,
86 // Windows-specific home directory variables
87 USERPROFILE: context.testDir,
88 HOMEDRIVE: path.parse(context.testDir).root,
89 HOMEPATH: path.relative(
90 path.parse(context.testDir).root,
91 context.testDir,
92 ),
93 ...env,
94 },
95 timeout,
96 reject: false,
97 input,
98 };
99
100 try {
101 // Run the wrapper via Node for cross-platform consistency
102 const result = await execaNode(context.cliPath, args, execOptions);
103
104 return {
105 stdout: result.stdout,
106 stderr: result.stderr,
107 exitCode: result.exitCode ?? 0,
108 };
109 } catch (error: any) {
110 if (!expectError) {
111 throw error;
112 }
113
114 return {
115 stdout: error.stdout || "",
116 stderr: error.stderr || "",
117 exitCode: error.exitCode ?? 1,
118 error,
119 };
120 }
121}
122
123/**
124 * Creates a test configuration file
125 */
126export async function createTestConfig(
127 context: CLITestContext,
128 config: any,
129): Promise<string> {
130 const configPath = path.join(context.testDir, "test-config.yaml");
131 const configContent =
132 typeof config === "string" ? config : JSON.stringify(config, null, 2);
133
134 await fs.writeFile(configPath, configContent);
135 context.configPath = configPath;
136
137 return configPath;
138}
139
140/**
141 * Creates a test rule file
142 */
143export async function createTestRule(
144 context: CLITestContext,
145 ruleName: string,
146 content: string,
147): Promise<string> {
148 const rulePath = path.join(context.testDir, `${ruleName}.md`);
149 await fs.writeFile(rulePath, content);
150 return rulePath;
151}
152
153/**
154 * Reads the session file if it exists
155 */
156export async function readSession(
157 context: CLITestContext,
158): Promise<any | null> {
159 try {
160 const sessionDir = path.join(context.testDir, ".continue", "sessions");
161 const files = await fs.readdir(sessionDir);
162
163 if (files.length === 0) {
164 return null;
165 }
166
167 // Get the most recent session file
168 const sessionFile = files.sort().pop()!;
169 const sessionPath = path.join(sessionDir, sessionFile);
170 const content = await fs.readFile(sessionPath, "utf-8");
171
172 return JSON.parse(content);
173 } catch {
174 return null;
175 }
176}
177
178/**
179 * Creates a mock session file
180 */
181export async function createMockSession(
182 context: CLITestContext,
183 messages: any[],
184): Promise<string> {
185 const sessionDir = path.join(context.testDir, ".continue", "sessions");
186 await fs.mkdir(sessionDir, { recursive: true });
187
188 const sessionId = `test-session-${Date.now()}`;
189 const sessionPath = path.join(sessionDir, `${sessionId}.json`);
190
191 const session = {
192 id: sessionId,
193 timestamp: new Date().toISOString(),
194 messages,
195 config: {},
196 };
197
198 await fs.writeFile(sessionPath, JSON.stringify(session, null, 2));
199 context.sessionPath = sessionPath;
200
201 return sessionPath;
202}
203
204/**
205 * Waits for a pattern in the output
206 */
207export function waitForPattern(
208 proc: Subprocess,
209 pattern: RegExp | string,
210 timeout: number = 5000,
211): Promise<string> {
212 return new Promise((resolve, reject) => {
213 let output = "";
214 const timer = setTimeout(() => {
215 proc.kill();
216 reject(new Error(`Timeout waiting for pattern: ${pattern}`));
217 }, timeout);
218
219 const checkOutput = (data: string) => {
220 output += data;
221 const match =
222 typeof pattern === "string"
223 ? output.includes(pattern)
224 : pattern.test(output);
225
226 if (match) {
227 clearTimeout(timer);
228 resolve(output);
229 }
230 };
231
232 proc.stdout?.on("data", checkOutput);
233 proc.stderr?.on("data", checkOutput);
234 });
235}
236
237/**
238 * Simulates user input in interactive mode
239 */
240export async function withInteractiveInput(
241 context: CLITestContext,
242 args: string[],
243 inputs: string[],
244): Promise<CLIRunResult> {
245 const proc = execaNode(context.cliPath, args, {
246 cwd: context.testDir,
247 env: {
248 ...process.env,
249 CONTINUE_CLI_TEST: "true",
250 HOME: context.testDir,
251 // Windows-specific home directory variables
252 USERPROFILE: context.testDir,
253 HOMEDRIVE: path.parse(context.testDir).root,
254 HOMEPATH: path.relative(
255 path.parse(context.testDir).root,
256 context.testDir,
257 ),
258 },
259 });
260
261 let stdout = "";
262 let stderr = "";
263
264 proc.stdout?.on("data", (data) => {
265 stdout += data;
266 });
267
268 proc.stderr?.on("data", (data) => {
269 stderr += data;
270 });
271
272 // Send inputs sequentially
273 for (const input of inputs) {
274 await new Promise((resolve) => setTimeout(resolve, 100)); // Small delay
275 proc.stdin?.write(input + "\n");
276 }
277
278 // End input
279 proc.stdin?.end();
280
281 try {
282 const result = await proc;
283 return {
284 stdout,
285 stderr,
286 exitCode: result.exitCode ?? 0,
287 };
288 } catch (error: any) {
289 return {
290 stdout,
291 stderr,
292 exitCode: error.exitCode ?? 1,
293 error,
294 };
295 }
296}