feat(hooks): Implement test fixtures (#6862)

This commit is contained in:
CandiedUniverse authored and GitHub committed 2025-10-15 11:42:32 -07:00
1 parent 7c51236aef
commit b09751b841
9 files changed
+319

No files matched your search

+120
View File
@@ -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
@@ -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);
@@ -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: ""
}));
@@ -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"
}));
@@ -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: ""
}));
@@ -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);
@@ -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: ""
}));
+66
View File
@@ -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}`
}));
}
@@ -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