From b09751b841b4bfbbc338eab7d4156776d5c8a381 Mon Sep 17 00:00:00 2001 From: CandiedUniverse <132302818+candieduniverse@users.noreply.github.com> Date: Wed, 15 Oct 2025 11:42:32 -0700 Subject: [PATCH] feat(hooks): Implement test fixtures (#6862) --- src/core/hooks/__tests__/fixtures/README.md | 120 ++++++++++++++++++ .../hooks/posttooluse/error/PostToolUse | 4 + .../hooks/posttooluse/success/PostToolUse | 7 + .../hooks/pretooluse/blocking/PreToolUse | 7 + .../pretooluse/context-injection/PreToolUse | 8 ++ .../hooks/pretooluse/error/PreToolUse | 4 + .../hooks/pretooluse/success/PreToolUse | 7 + .../__tests__/fixtures/template/HookName | 66 ++++++++++ .../__tests__/fixtures/template/README.md | 96 ++++++++++++++ 9 files changed, 319 insertions(+) create mode 100644 src/core/hooks/__tests__/fixtures/README.md create mode 100755 src/core/hooks/__tests__/fixtures/hooks/posttooluse/error/PostToolUse create mode 100755 src/core/hooks/__tests__/fixtures/hooks/posttooluse/success/PostToolUse create mode 100755 src/core/hooks/__tests__/fixtures/hooks/pretooluse/blocking/PreToolUse create mode 100755 src/core/hooks/__tests__/fixtures/hooks/pretooluse/context-injection/PreToolUse create mode 100755 src/core/hooks/__tests__/fixtures/hooks/pretooluse/error/PreToolUse create mode 100755 src/core/hooks/__tests__/fixtures/hooks/pretooluse/success/PreToolUse create mode 100755 src/core/hooks/__tests__/fixtures/template/HookName create mode 100644 src/core/hooks/__tests__/fixtures/template/README.md diff --git a/src/core/hooks/__tests__/fixtures/README.md b/src/core/hooks/__tests__/fixtures/README.md new file mode 100644 index 00000000..eeef3394 --- /dev/null +++ b/src/core/hooks/__tests__/fixtures/README.md @@ -0,0 +1,120 @@ +# Hook Test Fixtures + +This directory contains pre-written hook scripts for testing the Cline hooks system. + +## Directory Structure + +``` +fixtures/ +├── hooks/ +│ ├── pretooluse/ # PreToolUse hook fixtures +│ │ ├── success/ # Returns success immediately +│ │ ├── blocking/ # Blocks tool execution +│ │ ├── context-injection/ # Adds context with type prefix +│ │ └── error/ # Exits with error code +│ ├── posttooluse/ # PostToolUse hook fixtures +│ │ ├── success/ # Returns success immediately +│ │ └── error/ # Exits with error code +│ └── template/ # Template for new hooks +└── inputs/ # Sample input data (future) +``` + +## Using Fixtures in Tests + +### With loadFixture() + +The `loadFixture()` helper function copies a fixture to your test environment: + +```typescript +import { loadFixture } from '../test-utils' + +it("should work with real hook", async () => { + const { getEnv } = setupHookTests() + + await loadFixture("hooks/pretooluse/success", getEnv().tempDir) + + const factory = new HookFactory() + const runner = await factory.create("PreToolUse") + const result = await runner.run(buildPreToolUseInput({ toolName: "test_tool" })) + + result.shouldContinue.should.be.true() +}) +``` + +### Direct File Copy + +For more control, you can also manually copy fixture files. + +## Available Fixtures + +### PreToolUse Hooks + +#### `hooks/pretooluse/success` +- **Returns**: `{ shouldContinue: true, contextModification: "PreToolUse hook executed successfully", errorMessage: "" }` +- **Use for**: Testing happy path scenarios + +#### `hooks/pretooluse/blocking` +- **Returns**: `{ shouldContinue: false, contextModification: "", errorMessage: "Tool execution blocked by hook" }` +- **Use for**: Testing tool execution blocking + +#### `hooks/pretooluse/context-injection` +- **Returns**: `{ shouldContinue: true, contextModification: "WORKSPACE_RULES: Tool [toolName] requires review", errorMessage: "" }` +- **Use for**: Testing context injection with type prefixes +- **Note**: Dynamically includes tool name from input + +#### `hooks/pretooluse/error` +- **Behavior**: Prints error to stderr and exits with code 1 +- **Use for**: Testing error handling + +### PostToolUse Hooks + +#### `hooks/posttooluse/success` +- **Returns**: `{ shouldContinue: true, contextModification: "PostToolUse hook executed successfully", errorMessage: "" }` +- **Use for**: Testing PostToolUse execution + +#### `hooks/posttooluse/error` +- **Behavior**: Prints error to stderr and exits with code 1 +- **Use for**: Testing error handling in PostToolUse + +## Platform Considerations + +These fixtures are designed for the embedded shell architecture (similar to git hooks). They work uniformly across all platforms once the embedded shell is implemented. + +### Current Status +- **Linux/macOS**: Fully functional - executable scripts with shebangs +- **Windows**: Pending embedded shell implementation + +### Creating New Fixtures + +1. Create a new directory under the appropriate hook type +2. Add the hook script with shebang `#!/usr/bin/env node` +3. Make executable: `chmod +x HookName` +4. Update this README with the new fixture + +### Example: Creating a new fixture + +```bash +# Create directory +mkdir -p src/core/hooks/__tests__/fixtures/hooks/pretooluse/my-new-scenario + +# Create hook script +cat > src/core/hooks/__tests__/fixtures/hooks/pretooluse/my-new-scenario/PreToolUse << 'EOF' +#!/usr/bin/env node +const input = JSON.parse(require('fs').readFileSync(0, 'utf-8')); +console.log(JSON.stringify({ + shouldContinue: true, + contextModification: "My custom context", + errorMessage: "" +})); +EOF + +# Make executable +chmod +x src/core/hooks/__tests__/fixtures/hooks/pretooluse/my-new-scenario/PreToolUse +``` + +## Maintenance + +- Keep fixtures simple and focused on one scenario +- Fixtures are Node.js scripts that work across platforms +- Update this README when adding new fixtures +- Remove obsolete fixtures and update references diff --git a/src/core/hooks/__tests__/fixtures/hooks/posttooluse/error/PostToolUse b/src/core/hooks/__tests__/fixtures/hooks/posttooluse/error/PostToolUse new file mode 100755 index 00000000..c9ddd7ac --- /dev/null +++ b/src/core/hooks/__tests__/fixtures/hooks/posttooluse/error/PostToolUse @@ -0,0 +1,4 @@ +#!/usr/bin/env node +const input = JSON.parse(require('fs').readFileSync(0, 'utf-8')); +console.error("PostToolUse hook execution failed"); +process.exit(1); diff --git a/src/core/hooks/__tests__/fixtures/hooks/posttooluse/success/PostToolUse b/src/core/hooks/__tests__/fixtures/hooks/posttooluse/success/PostToolUse new file mode 100755 index 00000000..9e61d0ea --- /dev/null +++ b/src/core/hooks/__tests__/fixtures/hooks/posttooluse/success/PostToolUse @@ -0,0 +1,7 @@ +#!/usr/bin/env node +const input = JSON.parse(require('fs').readFileSync(0, 'utf-8')); +console.log(JSON.stringify({ + shouldContinue: true, + contextModification: "PostToolUse hook executed successfully", + errorMessage: "" +})); diff --git a/src/core/hooks/__tests__/fixtures/hooks/pretooluse/blocking/PreToolUse b/src/core/hooks/__tests__/fixtures/hooks/pretooluse/blocking/PreToolUse new file mode 100755 index 00000000..1c74edbc --- /dev/null +++ b/src/core/hooks/__tests__/fixtures/hooks/pretooluse/blocking/PreToolUse @@ -0,0 +1,7 @@ +#!/usr/bin/env node +const input = JSON.parse(require('fs').readFileSync(0, 'utf-8')); +console.log(JSON.stringify({ + shouldContinue: false, + contextModification: "", + errorMessage: "Tool execution blocked by hook" +})); diff --git a/src/core/hooks/__tests__/fixtures/hooks/pretooluse/context-injection/PreToolUse b/src/core/hooks/__tests__/fixtures/hooks/pretooluse/context-injection/PreToolUse new file mode 100755 index 00000000..9a74e804 --- /dev/null +++ b/src/core/hooks/__tests__/fixtures/hooks/pretooluse/context-injection/PreToolUse @@ -0,0 +1,8 @@ +#!/usr/bin/env node +const input = JSON.parse(require('fs').readFileSync(0, 'utf-8')); +const toolName = input.preToolUse?.toolName || 'unknown'; +console.log(JSON.stringify({ + shouldContinue: true, + contextModification: `WORKSPACE_RULES: Tool ${toolName} requires review`, + errorMessage: "" +})); diff --git a/src/core/hooks/__tests__/fixtures/hooks/pretooluse/error/PreToolUse b/src/core/hooks/__tests__/fixtures/hooks/pretooluse/error/PreToolUse new file mode 100755 index 00000000..f114a8c0 --- /dev/null +++ b/src/core/hooks/__tests__/fixtures/hooks/pretooluse/error/PreToolUse @@ -0,0 +1,4 @@ +#!/usr/bin/env node +const input = JSON.parse(require('fs').readFileSync(0, 'utf-8')); +console.error("Hook execution failed"); +process.exit(1); diff --git a/src/core/hooks/__tests__/fixtures/hooks/pretooluse/success/PreToolUse b/src/core/hooks/__tests__/fixtures/hooks/pretooluse/success/PreToolUse new file mode 100755 index 00000000..ac46c313 --- /dev/null +++ b/src/core/hooks/__tests__/fixtures/hooks/pretooluse/success/PreToolUse @@ -0,0 +1,7 @@ +#!/usr/bin/env node +const input = JSON.parse(require('fs').readFileSync(0, 'utf-8')); +console.log(JSON.stringify({ + shouldContinue: true, + contextModification: "PreToolUse hook executed successfully", + errorMessage: "" +})); diff --git a/src/core/hooks/__tests__/fixtures/template/HookName b/src/core/hooks/__tests__/fixtures/template/HookName new file mode 100755 index 00000000..c143b631 --- /dev/null +++ b/src/core/hooks/__tests__/fixtures/template/HookName @@ -0,0 +1,66 @@ +#!/usr/bin/env node + +/** + * TEMPLATE HOOK SCRIPT + * + * This is a template for creating new hook fixtures. + * Copy this file to create a new fixture script. + * + * Customize the logic below to implement your specific hook behavior. + */ + +try { + // Parse the input from stdin (what gets passed to the hook) + const input = JSON.parse(require('fs').readFileSync(0, 'utf-8')); + + // Extract relevant input data + // For PreToolUse hooks: + const { toolName, parameters } = input.preToolUse || {}; + // For PostToolUse hooks: + // const { toolName, parameters, result, success, executionTimeMs } = input.postToolUse || {}; + + // Common metadata (available in all hook types) + const { hookName: hookType, timestamp, taskId, workspaceRoots, userId } = input; + + // Initialize output variables + let shouldContinue = true; + let contextModification = ""; + let errorMessage = ""; + + // === CUSTOMIZE THIS LOGIC === + // Implement your hook logic here + + // Example: Simple success hook + contextModification = "TEMPLATE: Hook executed successfully"; + + // Example: Context injection based on tool name + if (toolName === "write_to_file") { + contextModification = "FILE_OPERATIONS: File modification operation"; + } else if (toolName === "run_command") { + contextModification = "SYSTEM_OPERATIONS: Command execution operation"; + } + + // Example: Validation/blocking + // if (!parameters?.path) { + // shouldContinue = false; + // errorMessage = "ERROR: Tool requires a 'path' parameter"; + // } + + // === END CUSTOM LOGIC === + + // Return the standardized output format + console.log(JSON.stringify({ + shouldContinue, + contextModification, + errorMessage + })); + +} catch (error) { + // Error handling - hooks should handle their own errors gracefully + const errorMessage = error instanceof Error ? error.message : String(error); + console.log(JSON.stringify({ + shouldContinue: false, + contextModification: "", + errorMessage: `HOOK_ERROR: ${errorMessage}` + })); +} diff --git a/src/core/hooks/__tests__/fixtures/template/README.md b/src/core/hooks/__tests__/fixtures/template/README.md new file mode 100644 index 00000000..2b822633 --- /dev/null +++ b/src/core/hooks/__tests__/fixtures/template/README.md @@ -0,0 +1,96 @@ +# Hook Template for New Fixtures + +This directory contains a template for creating new hook fixtures. When adding a new hook fixture, copy from this template and customize as needed. + +## Files in This Template + +- `HookName` - Hook script template (executable Node.js script) +- `README.md` - This file + +## How to Create a New Fixture + +### Step 1: Choose the Scenario Type + +Decide what your hook fixture should test: +- `success` - Returns success immediately +- `blocking` - Blocks tool execution +- `context-injection` - Adds context information +- `error` - Exits with error code + +### Step 2: Create the Directory Structure + +```bash +# Example for a new PreToolUse validation fixture +mkdir -p src/core/hooks/__tests__/fixtures/hooks/pretooluse/validation/ + +# Copy template file +cp src/core/hooks/__tests__/fixtures/template/HookName src/core/hooks/__tests__/fixtures/hooks/pretooluse/validation/PreToolUse + +# Make executable +chmod +x src/core/hooks/__tests__/fixtures/hooks/pretooluse/validation/PreToolUse +``` + +### Step 3: Customize the Hook Script + +Edit the new fixture file to implement your specific logic: + +```javascript +#!/usr/bin/env node + +const input = JSON.parse(require('fs').readFileSync(0, 'utf-8')); + +// Extract relevant data +const { toolName, parameters } = input.preToolUse; + +let shouldContinue = true; +let contextModification = ""; +let errorMessage = ""; + +// Your custom logic here +if (!parameters || !parameters.path) { + shouldContinue = false; + errorMessage = "ERROR: Tool requires a 'path' parameter"; +} else { + contextModification = "VALIDATION: Basic input validation passed"; +} + +// Return standardized output +console.log(JSON.stringify({ + shouldContinue, + contextModification, + errorMessage +})); +``` + +### Step 4: Update Documentation + +Add your new fixture to `fixtures/README.md` with: +- Fixture path +- What it returns +- What it's used for testing +- Any special behavior notes + +## Best Practices + +### Keep Fixtures Focused +- Test one specific scenario per fixture +- Use simple, easy-to-understand logic +- Document complex behavior with comments + +### Platform Compatibility +- Write portable Node.js code +- These fixtures work via embedded shell (like git hooks) +- Avoid platform-specific logic + +### Naming Conventions +- Use UPPERCASE for context type prefixes (e.g., `WORKSPACE_RULES:`, `FILE_OPERATIONS:`) +- Be descriptive about what the fixture tests +- Follow existing naming patterns in other fixtures + +## Examples from Existing Fixtures + +See the existing fixtures for real-world examples: +- `../hooks/pretooluse/success/` - Simple success case +- `../hooks/pretooluse/blocking/` - How to block execution +- `../hooks/pretooluse/context-injection/` - How to inject context +- `../hooks/pretooluse/error/` - How to return errors