From 54d4c448224923ecfe7e9bc767025892050ffe7c Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 19:02:41 -0700 Subject: [PATCH] Revert "attempt to fix tests" This reverts commit 8ff750dbfd0c3ea61c5562022fa87c282b36bf78. --- src/commands/chat.ts | 18 +- src/commands/login.ts | 3 +- src/e2e/basic-commands.test.ts | 2 +- src/index.ts | 7 +- src/test-helpers/TESTING_GUIDE.md | 279 ---------------------------- src/test-helpers/cli-helpers.ts | 8 - src/test-helpers/mock-llm-server.ts | 4 +- src/test-helpers/process-runner.ts | 151 --------------- src/test-helpers/wait-for-output.ts | 15 -- src/util/exit-handler.ts | 24 --- 10 files changed, 9 insertions(+), 502 deletions(-) delete mode 100644 src/test-helpers/TESTING_GUIDE.md delete mode 100644 src/test-helpers/process-runner.ts delete mode 100644 src/test-helpers/wait-for-output.ts delete mode 100644 src/util/exit-handler.ts diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 8a6f9e506..41216ad1c 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -11,7 +11,6 @@ import { constructSystemMessage } from "../systemMessage.js"; import { startTUIChat } from "../ui/index.js"; import { formatError } from "../util/formatError.js"; import logger from "../util/logger.js"; -import { safeExit } from "../util/exit-handler.js"; export interface ChatOptions { headless?: boolean; @@ -127,15 +126,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { // In headless mode, only print the final response if (options.headless && finalResponse.trim()) { - // Write to stdout and ensure it's flushed - await new Promise((resolve) => { - const output = finalResponse + '\n'; - if (process.stdout.write(output)) { - resolve(); - } else { - process.stdout.once('drain', resolve); - } - }); + console.log(finalResponse); } // Save session after each successful response @@ -149,13 +140,8 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { } } } - - // Ensure proper exit in headless mode - if (options.headless) { - await safeExit(0); - } } catch (error: any) { logger.error(chalk.red(`Fatal error: ${formatError(error)}`)); - await safeExit(1); + process.exit(1); } } \ No newline at end of file diff --git a/src/commands/login.ts b/src/commands/login.ts index b63f13694..d7d96a827 100644 --- a/src/commands/login.ts +++ b/src/commands/login.ts @@ -1,6 +1,5 @@ import chalk from "chalk"; import { login as workosLogin } from "../auth/workos.js"; -import { safeExit } from "../util/exit-handler.js"; export async function login() { console.info(chalk.yellow("Logging in to Continue...")); @@ -10,6 +9,6 @@ export async function login() { console.info(chalk.green("Successfully logged in!")); } catch (error: any) { console.error(chalk.red(`Login failed: ${error.message}`)); - await safeExit(1); + process.exit(1); } } diff --git a/src/e2e/basic-commands.test.ts b/src/e2e/basic-commands.test.ts index de6d13439..d2e99ff44 100644 --- a/src/e2e/basic-commands.test.ts +++ b/src/e2e/basic-commands.test.ts @@ -21,7 +21,7 @@ describe("E2E: Basic Commands", () => { const result = await runCLI(context, { args: ["--version"] }); expect(result.exitCode).toBe(0); - expect(result.stdout.trim()).toBe(getVersion()); + expect(result.stdout).toBe(getVersion()); expect(result.stderr).toBe(""); }); }); diff --git a/src/index.ts b/src/index.ts index 5fc300dcd..9a0eb78cd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,7 +6,6 @@ import { login } from "./commands/login.js"; import { logout } from "./commands/logout.js"; import { getVersion } from "./version.js"; import logger from "./util/logger.js"; -import { safeExit } from "./util/exit-handler.js"; // Add global error handlers to prevent uncaught errors from crashing the process process.on("unhandledRejection", (reason, promise) => { @@ -82,10 +81,10 @@ program }); // Handle unknown commands -program.on("command:*", async () => { +program.on("command:*", () => { console.error(`Error: Unknown command '${program.args.join(" ")}'\n`); program.outputHelp(); - await safeExit(1); + process.exit(1); }); // Parse arguments and handle errors @@ -93,5 +92,5 @@ try { program.parse(); } catch (error) { console.error(error); - await safeExit(1); + process.exit(1); } diff --git a/src/test-helpers/TESTING_GUIDE.md b/src/test-helpers/TESTING_GUIDE.md deleted file mode 100644 index 0218d232a..000000000 --- a/src/test-helpers/TESTING_GUIDE.md +++ /dev/null @@ -1,279 +0,0 @@ -# Testing Guide for Continue CLI - -This guide explains how to write reliable cross-platform tests for the Continue CLI, with special attention to Windows compatibility. - -## Overview - -The Continue CLI test suite uses standard test helpers with minimal Windows-specific accommodations. The CLI itself handles output flushing properly, ensuring tests work reliably across all platforms. - -Key considerations: -- Windows may need slightly more time for process cleanup -- Output should be trimmed when comparing exact strings -- Mock servers should be properly cleaned up - -## Key Test Helpers - -### 1. CLI Test Context (`cli-helpers.ts`) - -Always use the provided test context and helpers: - -```typescript -import { - createTestContext, - cleanupTestContext, - runCLI, -} from "../test-helpers/cli-helpers.js"; - -describe("Your Test Suite", () => { - let context: any; - - beforeEach(async () => { - context = await createTestContext(); - }); - - afterEach(async () => { - await cleanupTestContext(context); - }); - - it("should do something", async () => { - const result = await runCLI(context, { - args: ["-p", "Hello"], - timeout: 15000, // Optional: default is 10000ms - }); - - expect(result.stdout).toContain("Expected output"); - expect(result.exitCode).toBe(0); - }); -}); -``` - -**Important:** Always use `runCLI()` instead of directly spawning processes. It handles: -- Cross-platform process execution -- Proper output capture -- Windows-specific environment variables -- Automatic cleanup - -### 2. Mock LLM Server (`mock-llm-server.ts`) - -For tests that need to mock LLM responses: - -```typescript -import { - setupMockLLMTest, - cleanupMockLLMServer, -} from "../test-helpers/mock-llm-server.js"; - -describe("LLM Test", () => { - let context: any; - let mockServer: MockLLMServer; - - beforeEach(async () => { - context = await createTestContext(); - mockServer = await setupMockLLMTest(context, { - response: "Mock response", - // or dynamic responses: - response: (prompt: string) => { - if (prompt.includes("weather")) { - return "It's sunny!"; - } - return "Default response"; - }, - }); - }); - - afterEach(async () => { - await cleanupMockLLMServer(mockServer); - await cleanupTestContext(context); - }); -}); -``` - -**Important:** Always clean up mock servers in `afterEach` to prevent port conflicts and hanging processes. - -## Best Practices - -### 1. Test Timeouts - -- Default timeout is 10 seconds -- For tests involving network operations or multiple CLI calls, use 15-20 seconds -- Example: `runCLI(context, { args: [...], timeout: 15000 })` - -### 2. Output Assertions - -Always trim output when comparing exact strings to handle platform differences: - -```typescript -// Good -expect(result.stdout.trim()).toBe("Expected output"); - -// Bad - may fail due to trailing whitespace -expect(result.stdout).toBe("Expected output"); - -// For partial matches, use toContain (no trim needed) -expect(result.stdout).toContain("partial match"); -``` - -### 3. Multiple Mock Servers - -When using multiple mock servers, track them for cleanup: - -```typescript -let extraServers: MockLLMServer[] = []; - -beforeEach(async () => { - extraServers = []; -}); - -afterEach(async () => { - // Clean up extra servers first - await Promise.all(extraServers.map(server => cleanupMockLLMServer(server))); - extraServers = []; - - // Then clean up main server and context - if (mockServer) { - await cleanupMockLLMServer(mockServer); - } - await cleanupTestContext(context); -}); - -it("test with multiple servers", async () => { - const server2 = await createMockLLMServer({ response: "Server 2" }); - extraServers.push(server2); - // ... test logic -}); -``` - -### 4. Session and File Management - -The test context provides an isolated temporary directory. Use it for all file operations: - -```typescript -// Good - uses test directory -const configPath = path.join(context.testDir, "config.yaml"); - -// Bad - uses system directories -const configPath = "/tmp/config.yaml"; -``` - -### 5. Environment Variables - -Test-specific environment variables are automatically set. You can add more: - -```typescript -const result = await runCLI(context, { - args: ["-p", "Hello"], - env: { - MY_CUSTOM_VAR: "value", - // These are set automatically: - // CONTINUE_CLI_TEST: "true" - // HOME/USERPROFILE: context.testDir - }, -}); -``` - -### 6. Error Handling - -Use `expectError` for tests that should fail: - -```typescript -const result = await runCLI(context, { - args: ["--invalid-flag"], - expectError: true, -}); - -expect(result.exitCode).not.toBe(0); -expect(result.stderr).toContain("error message"); -``` - -## Common Pitfalls to Avoid - -1. **Don't use `process.exit()` in test code** - Use the CLI's built-in exit handling -2. **Don't use `execSync` or `spawn` directly** - Use `runCLI()` -3. **Don't hardcode paths** - Use `context.testDir` for file operations -4. **Don't skip cleanup** - Always clean up servers and contexts -5. **Don't use short timeouts** - Windows needs more time for process operations - -## Platform-Specific Considerations - -### Windows -- Process creation is slower -- Output buffering behaves differently -- Socket cleanup requires explicit connection destruction -- File paths must use forward slashes or `path.join()` - -### macOS/Linux -- Generally faster process creation -- More predictable output flushing -- Cleaner socket cleanup - -## Debugging Failed Tests - -1. **Check for timing issues**: Increase timeouts -2. **Check for cleanup issues**: Ensure all servers are properly cleaned up -3. **Check output format**: Use `.trim()` for exact comparisons -4. **Check file paths**: Use `path.join()` for cross-platform paths -5. **Enable verbose logging**: Set `NODE_ENV=test` for more detailed output - -## Example: Complete Test File - -```typescript -import { - cleanupTestContext, - createTestContext, - runCLI, -} from "../test-helpers/cli-helpers.js"; -import { - setupMockLLMTest, - cleanupMockLLMServer, - type MockLLMServer, -} from "../test-helpers/mock-llm-server.js"; - -describe("E2E: My Feature", () => { - let context: any; - let mockServer: MockLLMServer; - - beforeEach(async () => { - context = await createTestContext(); - mockServer = await setupMockLLMTest(context, { - response: "Test response", - }); - }); - - afterEach(async () => { - await cleanupMockLLMServer(mockServer); - await cleanupTestContext(context); - }); - - it("should handle basic prompt", async () => { - const result = await runCLI(context, { - args: ["-p", "Hello", "--config", context.configPath], - timeout: 15000, - }); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toContain("Test response"); - expect(mockServer.requests).toHaveLength(1); - }); - - it("should handle errors gracefully", async () => { - const result = await runCLI(context, { - args: ["--invalid-command"], - expectError: true, - }); - - expect(result.exitCode).not.toBe(0); - }); -}); -``` - -## Summary - -By following these guidelines and using the provided test helpers, you can write reliable tests that work across all platforms. The key is to: - -1. Always use the provided test helpers -2. Clean up resources properly -3. Handle output with platform differences in mind -4. Use appropriate timeouts -5. Test error cases explicitly - -Remember: The test helpers handle the complexity of cross-platform compatibility, so you can focus on testing your feature's behavior. \ No newline at end of file diff --git a/src/test-helpers/cli-helpers.ts b/src/test-helpers/cli-helpers.ts index f5d10ddeb..3b9a9d3d3 100644 --- a/src/test-helpers/cli-helpers.ts +++ b/src/test-helpers/cli-helpers.ts @@ -84,19 +84,11 @@ export async function runCLI( timeout, reject: false, input, - // Ensure proper buffering - buffer: true, - stripFinalNewline: false, }; try { const result = await execaNode(context.cliPath, args, execOptions); - // Add a small delay on Windows to ensure output is captured - if (process.platform === "win32") { - await new Promise(resolve => setTimeout(resolve, 50)); - } - return { stdout: result.stdout, stderr: result.stderr, diff --git a/src/test-helpers/mock-llm-server.ts b/src/test-helpers/mock-llm-server.ts index ec756a341..117d3d330 100644 --- a/src/test-helpers/mock-llm-server.ts +++ b/src/test-helpers/mock-llm-server.ts @@ -248,7 +248,7 @@ export async function cleanupMockLLMServer( } }; - // Force close all connections if method exists (Node 18.2+) + // Force close all connections if method exists if (typeof mockServer.server.closeAllConnections === "function") { mockServer.server.closeAllConnections(); } @@ -266,6 +266,6 @@ export async function cleanupMockLLMServer( } // Fallback timeout to ensure cleanup doesn't hang - setTimeout(resolveOnce, 200); + setTimeout(resolveOnce, 500); }); } diff --git a/src/test-helpers/process-runner.ts b/src/test-helpers/process-runner.ts deleted file mode 100644 index d2ed6594a..000000000 --- a/src/test-helpers/process-runner.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { spawn, type ChildProcess } from "child_process"; -import { once } from "events"; -import * as path from "path"; -import * as os from "os"; - -export interface ProcessRunOptions { - args?: string[]; - env?: Record; - cwd?: string; - timeout?: number; - input?: string; -} - -export interface ProcessRunResult { - stdout: string; - stderr: string; - exitCode: number; - error?: Error; -} - -/** - * Cross-platform process runner that handles Windows-specific issues - * This replaces execaNode for more reliable test execution - */ -export class ProcessRunner { - private process: ChildProcess | null = null; - private stdout: string[] = []; - private stderr: string[] = []; - private isWindows = os.platform() === "win32"; - - async run( - scriptPath: string, - options: ProcessRunOptions = {} - ): Promise { - const { - args = [], - env = {}, - cwd = process.cwd(), - timeout = 10000, - input, - } = options; - - return new Promise((resolve, reject) => { - // For Windows, we need to explicitly use node to run the script - const command = this.isWindows ? process.execPath : process.execPath; - const processArgs = [scriptPath, ...args]; - - // Spawn the process with proper options - this.process = spawn(command, processArgs, { - cwd, - env: { - ...process.env, - ...env, - // Force color output even in non-TTY environments - FORCE_COLOR: "1", - // Ensure Node.js doesn't buffer output - NODE_NO_READLINE: "1", - }, - stdio: ["pipe", "pipe", "pipe"], - // Windows-specific options - windowsHide: true, - shell: false, - }); - - let timeoutId: NodeJS.Timeout | null = null; - let processExited = false; - - // Set up timeout - if (timeout > 0) { - timeoutId = setTimeout(() => { - if (!processExited && this.process) { - this.process.kill("SIGTERM"); - setTimeout(() => { - if (!processExited && this.process) { - this.process.kill("SIGKILL"); - } - }, 1000); - reject(new Error(`Process timed out after ${timeout}ms`)); - } - }, timeout); - } - - // Collect stdout - this.process.stdout?.on("data", (data) => { - const str = data.toString(); - this.stdout.push(str); - }); - - // Collect stderr - this.process.stderr?.on("data", (data) => { - const str = data.toString(); - this.stderr.push(str); - }); - - // Handle process exit - this.process.on("exit", (code, signal) => { - processExited = true; - if (timeoutId) clearTimeout(timeoutId); - - // Windows needs more time to flush output - const flushDelay = this.isWindows ? 100 : 10; - - // Give streams a chance to flush - setTimeout(() => { - resolve({ - stdout: this.stdout.join(""), - stderr: this.stderr.join(""), - exitCode: code ?? (signal ? 1 : 0), - }); - }, flushDelay); - }); - - // Handle process errors - this.process.on("error", (error) => { - processExited = true; - if (timeoutId) clearTimeout(timeoutId); - reject(error); - }); - - // Send input if provided - if (input && this.process.stdin) { - this.process.stdin.write(input); - this.process.stdin.end(); - } - }); - } - - /** - * Forcefully kill the process if it's still running - */ - kill(): void { - if (this.process && !this.process.killed) { - this.process.kill("SIGKILL"); - } - } -} - -/** - * Helper function to run a Node.js script with proper Windows handling - */ -export async function runNodeScript( - scriptPath: string, - options: ProcessRunOptions = {} -): Promise { - const runner = new ProcessRunner(); - try { - return await runner.run(scriptPath, options); - } finally { - runner.kill(); // Ensure cleanup - } -} \ No newline at end of file diff --git a/src/test-helpers/wait-for-output.ts b/src/test-helpers/wait-for-output.ts deleted file mode 100644 index f4d0de48d..000000000 --- a/src/test-helpers/wait-for-output.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Waits for process output to stabilize - * This helps ensure all output is captured on Windows - */ -export async function waitForOutput(timeout: number = 100): Promise { - return new Promise((resolve) => { - setTimeout(resolve, timeout); - }); -} - -/** - * Process exit delay for tests - * Windows needs extra time to flush output buffers - */ -export const TEST_EXIT_DELAY = process.platform === "win32" ? 200 : 50; \ No newline at end of file diff --git a/src/util/exit-handler.ts b/src/util/exit-handler.ts deleted file mode 100644 index d561fc25f..000000000 --- a/src/util/exit-handler.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Ensures proper process exit with flushed output streams - * This is crucial for Windows compatibility where output may be buffered - */ -export async function safeExit(code: number = 0): Promise { - // Flush stdout - if (process.stdout && !process.stdout.destroyed) { - await new Promise((resolve) => { - process.stdout.write("", () => resolve()); - }); - } - - // Flush stderr - if (process.stderr && !process.stderr.destroyed) { - await new Promise((resolve) => { - process.stderr.write("", () => resolve()); - }); - } - - // Give OS a moment to flush buffers - await new Promise((resolve) => setImmediate(resolve)); - - process.exit(code); -} \ No newline at end of file