attempt to fix tests

This commit is contained in:
Nate 2025-07-19 18:59:46 -07:00
parent 5853c38a54
commit 8ff750dbfd
10 changed files with 502 additions and 9 deletions

View file

@ -11,6 +11,7 @@ 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;
@ -126,7 +127,15 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
// In headless mode, only print the final response
if (options.headless && finalResponse.trim()) {
console.log(finalResponse);
// Write to stdout and ensure it's flushed
await new Promise<void>((resolve) => {
const output = finalResponse + '\n';
if (process.stdout.write(output)) {
resolve();
} else {
process.stdout.once('drain', resolve);
}
});
}
// Save session after each successful response
@ -140,8 +149,13 @@ 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)}`));
process.exit(1);
await safeExit(1);
}
}

View file

@ -1,5 +1,6 @@
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..."));
@ -9,6 +10,6 @@ export async function login() {
console.info(chalk.green("Successfully logged in!"));
} catch (error: any) {
console.error(chalk.red(`Login failed: ${error.message}`));
process.exit(1);
await safeExit(1);
}
}

View file

@ -21,7 +21,7 @@ describe("E2E: Basic Commands", () => {
const result = await runCLI(context, { args: ["--version"] });
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe(getVersion());
expect(result.stdout.trim()).toBe(getVersion());
expect(result.stderr).toBe("");
});
});

View file

@ -6,6 +6,7 @@ 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) => {
@ -81,10 +82,10 @@ program
});
// Handle unknown commands
program.on("command:*", () => {
program.on("command:*", async () => {
console.error(`Error: Unknown command '${program.args.join(" ")}'\n`);
program.outputHelp();
process.exit(1);
await safeExit(1);
});
// Parse arguments and handle errors
@ -92,5 +93,5 @@ try {
program.parse();
} catch (error) {
console.error(error);
process.exit(1);
await safeExit(1);
}

View file

@ -0,0 +1,279 @@
# 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.

View file

@ -84,11 +84,19 @@ 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,

View file

@ -248,7 +248,7 @@ export async function cleanupMockLLMServer(
}
};
// Force close all connections if method exists
// Force close all connections if method exists (Node 18.2+)
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, 500);
setTimeout(resolveOnce, 200);
});
}

View file

@ -0,0 +1,151 @@
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<string, string>;
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<ProcessRunResult> {
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<ProcessRunResult> {
const runner = new ProcessRunner();
try {
return await runner.run(scriptPath, options);
} finally {
runner.kill(); // Ensure cleanup
}
}

View file

@ -0,0 +1,15 @@
/**
* Waits for process output to stabilize
* This helps ensure all output is captured on Windows
*/
export async function waitForOutput(timeout: number = 100): Promise<void> {
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;

24
src/util/exit-handler.ts Normal file
View file

@ -0,0 +1,24 @@
/**
* 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<never> {
// Flush stdout
if (process.stdout && !process.stdout.destroyed) {
await new Promise<void>((resolve) => {
process.stdout.write("", () => resolve());
});
}
// Flush stderr
if (process.stderr && !process.stderr.destroyed) {
await new Promise<void>((resolve) => {
process.stderr.write("", () => resolve());
});
}
// Give OS a moment to flush buffers
await new Promise((resolve) => setImmediate(resolve));
process.exit(code);
}