
unit-testing
Unit and integration test automation for Python and JavaScript with agent-driven debugging support.
- version
- 1.2.0
- GitHub stars
- 126
What it does
- Adds
/test-generatefor generating unit test suites from code analysis in Python, JavaScript, TypeScript, Java, and Go - Creates mock objects for dependencies and produces a coverage gap analysis for an existing module
- Provides a
test-automatoragent for testing strategy, CI/CD integration, and mutation testing with Allure or TestRail reporting - Includes a
debuggeragent that captures stack traces, isolates failures, and proposes minimal fixes with prevention notes
Add marketplace
/plugin marketplace add HermeticOrmus/LibreUIUX-Claude-CodeRun it inside Claude Code once, then install the plugin below.
Install
/plugin install unit-testing@libreuiuxRun it inside Claude Code after adding the marketplace.
Files
Discovered from sourceAutomated Unit Test Generation
You are a test automation expert specializing in generating comprehensive, maintainable unit tests across multiple languages and frameworks. Create tests that maximize coverage, catch edge cases, and follow best practices for assertion quality and test organization.
Context
The user needs automated test generation that analyzes code structure, identifies test scenarios, and creates high-quality unit tests with proper mocking, assertions, and edge case coverage. Focus on framework-specific patterns and maintainable test suites.
Requirements
$ARGUMENTS
Instructions
1. Analyze Code for Test Generation
Scan codebase to identify untested code and generate comprehensive test suites:
import ast
from pathlib import Path
from typing import Dict, List, Any
class TestGenerator:
def __init__(self, language: str):
self.language = language
self.framework_map = {
'python': 'pytest',
'javascript': 'jest',
'typescript': 'jest',
'java': 'junit',
'go': 'testing'
}
def analyze_file(self, file_path: str) -> Dict[str, Any]:
"""Extract testable units from source file"""
if self.language == 'python':
return self._analyze_python(file_path)
elif self.language in ['javascript', 'typescript']:
return self._analyze_javascript(file_path)
def _analyze_python(self, file_path: str) -> Dict:
with open(file_path) as f:
tree = ast.parse(f.read())
functions = []
classes = []
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
functions.append({
'name': node.name,
'args': [arg.arg for arg in node.args.args],
'returns': ast.unparse(node.returns) if node.returns else None,
'decorators': [ast.unparse(d) for d in node.decorator_list],
'docstring': ast.get_docstring(node),
'complexity': self._calculate_complexity(node)
})
elif isinstance(node, ast.ClassDef):
methods = [n.name for n in node.body if isinstance(n, ast.FunctionDef)]
classes.append({
'name': node.name,
'methods': methods,
'bases': [ast.unparse(base) for base in node.bases]
})
return {'functions': functions, 'classes': classes, 'file': file_path}
2. Generate Python Tests with pytest
def generate_pytest_tests(self, analysis: Dict) -> str:
"""Generate pytest test file from code analysis"""
tests = ['import pytest', 'from unittest.mock import Mock, patch', '']
module_name = Path(analysis['file']).stem
tests.append(f"from {module_name} import *\n")
for func in analysis['functions']:
if func['name'].startswith('_'):
continue
test_class = self._generate_function_tests(func)
tests.append(test_class)
for cls in analysis['classes']:
test_class = self._generate_class_tests(cls)
tests.append(test_class)
return '\n'.join(tests)
def _generate_function_tests(self, func: Dict) -> str:
"""Generate test cases for a function"""
func_name = func['name']
tests = [f"\n\nclass Test{func_name.title()}:"]
# Happy path test
tests.append(f" def test_{func_name}_success(self):")
tests.append(f" result = {func_name}({self._generate_mock_args(func['args'])})")
tests.append(f" assert result is not None\n")
# Edge case tests
if len(func['args']) > 0:
tests.append(f" def test_{func_name}_with_empty_input(self):")
tests.append(f" with pytest.raises((ValueError, TypeError)):")
tests.append(f" {func_name}({self._generate_empty_args(func['args'])})\n")
# Exception handling test
tests.append(f" def test_{func_name}_handles_errors(self):")
tests.append(f" with pytest.raises(Exception):")
tests.append(f" {func_name}({self._generate_invalid_args(func['args'])})\n")
return '\n'.join(tests)
def _generate_class_tests(self, cls: Dict) -> str:
"""Generate test cases for a class"""
tests = [f"\n\nclass Test{cls['name']}:"]
tests.append(f" @pytest.fixture")
tests.append(f" def instance(self):")
tests.append(f" return {cls['name']}()\n")
for method in cls['methods']:
if method.startswith('_') and method != '__init__':
continue
tests.append(f" def test_{method}(self, instance):")
tests.append(f" result = instance.{method}()")
tests.append(f" assert result is not None\n")
return '\n'.join(tests)
3. Generate JavaScript/TypeScript Tests with Jest
interface TestCase {
name: string;
setup?: string;
execution: string;
assertions: string[];
}
class JestTestGenerator {
generateTests(functionName: string, params: string[]): string {
const tests: TestCase[] = [
{
name: `${functionName} returns expected result with valid input`,
execution: `const result = ${functionName}(${this.generateMockParams(params)})`,
assertions: ['expect(result).toBeDefined()', 'expect(result).not.toBeNull()']
},
{
name: `${functionName} handles null input gracefully`,
execution: `const result = ${functionName}(null)`,
assertions: ['expect(result).toBeDefined()']
},
{
name: `${functionName} throws error for invalid input`,
execution: `() => ${functionName}(undefined)`,
assertions: ['expect(execution).toThrow()']
}
];
return this.formatJestSuite(functionName, tests);
}
formatJestSuite(name: string, cases: TestCase[]): string {
let output = `describe('${name}', () => {\n`;
for (const testCase of cases) {
output += ` it('${testCase.name}', () => {\n`;
if (testCase.setup) {
output += ` ${testCase.setup}\n`;
}
output += ` const execution = ${testCase.execution};\n`;
for (const assertion of testCase.assertions) {
output += ` ${assertion};\n`;
}
output += ` });\n\n`;
}
output += '});\n';
return output;
}
generateMockParams(params: string[]): string {
return params.map(p => `mock${p.charAt(0).toUpperCase() + p.slice(1)}`).join(', ');
}
}
4. Generate React Component Tests
function generateReactComponentTest(componentName: string): string {
return `
import { render, screen, fireEvent } from '@testing-library/react';
import { ${componentName} } from './${componentName}';
describe('${componentName}', () => {
it('renders without crashing', () => {
render(<${componentName} />);
expect(screen.getByRole('main')).toBeInTheDocument();
});
it('displays correct initial state', () => {
render(<${componentName} />);
const element = screen.getByTestId('${componentName.toLowerCase()}');
expect(element).toBeVisible();
});
it('handles user interaction', () => {
render(<${componentName} />);
const button = screen.getByRole('button');
fireEvent.click(button);
expect(screen.getByText(/clicked/i)).toBeInTheDocument();
});
it('updates props correctly', () => {
const { rerender } = render(<${componentName} value="initial" />);
expect(screen.getByText('initial')).toBeInTheDocument();
rerender(<${componentName} value="updated" />);
expect(screen.getByText('updated')).toBeInTheDocument();
});
});
`;
}
5. Coverage Analysis and Gap Detection
import subprocess
import json
class CoverageAnalyzer:
def analyze_coverage(self, test_command: str) -> Dict:
"""Run tests with coverage and identify gaps"""
result = subprocess.run(
[test_command, '--coverage', '--json'],
capture_output=True,
text=True
)
coverage_data = json.loads(result.stdout)
gaps = self.identify_coverage_gaps(coverage_data)
return {
'overall_coverage': coverage_data.get('totals', {}).get('percent_covered', 0),
'uncovered_lines': gaps,
'files_below_threshold': self.find_low_coverage_files(coverage_data, 80)
}
def identify_coverage_gaps(self, coverage: Dict) -> List[Dict]:
"""Find specific lines/functions without test coverage"""
gaps = []
for file_path, data in coverage.get('files', {}).items():
missing_lines = data.get('missing_lines', [])
if missing_lines:
gaps.append({
'file': file_path,
'lines': missing_lines,
'functions': data.get('excluded_lines', [])
})
return gaps
def generate_tests_for_gaps(self, gaps: List[Dict]) -> str:
"""Generate tests specifically for uncovered code"""
tests = []
for gap in gaps:
test_code = self.create_targeted_test(gap)
tests.append(test_code)
return '\n\n'.join(tests)
6. Mock Generation
def generate_mock_objects(self, dependencies: List[str]) -> str:
"""Generate mock objects for external dependencies"""
mocks = ['from unittest.mock import Mock, MagicMock, patch\n']
for dep in dependencies:
mocks.append(f"@pytest.fixture")
mocks.append(f"def mock_{dep}():")
mocks.append(f" mock = Mock(spec={dep})")
mocks.append(f" mock.method.return_value = 'mocked_result'")
mocks.append(f" return mock\n")
return '\n'.join(mocks)
Output Format
- Test Files: Complete test suites ready to run
- Coverage Report: Current coverage with gaps identified
- Mock Objects: Fixtures for external dependencies
- Test Documentation: Explanation of test scenarios
- CI Integration: Commands to run tests in pipeline
Focus on generating maintainable, comprehensive tests that catch bugs early and provide confidence in code changes.
Readme
Unit Testing
Agents and a command for automated test generation, debugging, and AI-powered test automation across languages and frameworks.
Overview
This plugin provides core testing infrastructure used both directly and by other plugins (notably tdd-workflows). It includes a test automation agent with deep expertise in modern frameworks, AI-powered testing, and self-healing tests, a debugger agent for root cause analysis, and a command for automated unit test generation from code analysis. Use this plugin when writing tests, debugging failures, setting up test automation infrastructure, or generating test coverage for existing code.
Contents
Agents
-
test-automator -- Expert test automation engineer covering AI-powered testing (self-healing tests, visual AI), modern frameworks (Playwright, Appium, K6, Pact), TDD cycle support (both Chicago and London schools), CI/CD pipeline integration, performance and load testing, test data management, cross-platform testing, mutation testing, and comprehensive reporting with Allure/TestRail. Runs on Haiku for fast iteration.
-
debugger -- Debugging specialist for errors, test failures, and unexpected behavior. Follows a structured process: capture error and stack trace, identify reproduction steps, isolate failure location, implement minimal fix, and verify the solution. Provides root cause explanation, supporting evidence, specific code fixes, and prevention recommendations. Runs on Sonnet for thorough analysis.
Commands
- test-generate -- Automated unit test generation command. Analyzes code structure to identify testable units (functions, classes, methods), generates framework-appropriate test suites (pytest, Jest, JUnit, Go testing), creates mock objects for dependencies, and produces coverage gap analysis. Supports Python, JavaScript/TypeScript, Java, Go, and React component testing with @testing-library.
Skills
None
Usage
Install this plugin into your Claude Code project:
claude plugin install unit-testing
Generate tests for a file or module:
/test-generate src/services/auth.ts
The debugger agent activates proactively when encountering errors or test failures. The test-automator is used both directly for testing strategy questions and by the tdd-workflows plugin as a delegate for test creation and execution.
Related Plugins
- tdd-workflows -- Builds on this plugin's agents to implement full red-green-refactor TDD cycles with strict discipline enforcement.
- shell-scripting -- Includes Bats testing patterns for shell-specific test automation.
- systems-programming -- Language-specific testing approaches for C (CUnit), C++ (Google Test), Go (testing package), and Rust (built-in test framework).
Details
- Marketplace
- HermeticOrmus/LibreUIUX-Claude-Code
- Source
- plugins/unit-testing
- Author
- Seth Hobson
- Category
- Testing
- License
- MIT
- Keywords
- testing, unit-tests, python, javascript, automation
- Listed since
- Apr 7, 2026
More from HermeticOrmus/LibreUIUX-Claude-Code
All 71- vibe-codingv1.0.0
- web-scriptingv1.2.0
- accessibility-compliancev1.2.0
- agent-orchestrationv1.2.0
- api-scaffoldingv1.2.1
- api-testing-observabilityv1.2.0
- application-performancev1.2.1
- archetypal-alchemyv1.0.0
- arm-cortex-microcontrollersv1.2.0
- backend-api-securityv1.2.0
- backend-developmentv1.2.3
- blockchain-web3v1.2.1
- business-analyticsv1.2.0
- cicd-automationv1.2.1
- cloud-infrastructurev1.2.1
- code-documentationv1.2.0
- code-refactoringv1.2.0
- code-review-aiv1.2.0
- codebase-cleanupv1.2.0
- comprehensive-reviewv1.2.1
- content-marketingv1.2.0
- context-managementv1.2.0
- customer-sales-automationv1.2.0
- data-engineeringv1.2.1
Similar to unit-testing
More Testing & QA
testing-suitedavila7/claude-code-templates24.2K starsComprehensive testing toolkit with E2E, unit, integration, and visual testing automation
jutsu-pytestTheBushidoCollective/han201 starsComprehensive Pytest testing framework skills for Python projects with fixtures, plugins, and advanced testing patterns.
testing-strategiesmiles990/claude-software-skills26 starsUnit, integration, E2E testing and TDD practices
unit-test-generatorglincker/claude-code-marketplace38 starsGenerate comprehensive unit tests for multiple languages
jestTheBushidoCollective/han201 starsComprehensive Jest testing framework skills for JavaScript and TypeScript projects.