Elffuss BraidHub

kikocis/continue public

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