Analyze existing test suites and source code to suggest additional unit tests that improve test coverage. Use this skill when working with test files and source code to identify untested code paths, missing edge cases, uncovered branches, untested error conditions, and gaps in test coverage. Supports major testing frameworks (pytest, Jest, JUnit, Go testing, etc.) and generates targeted test suggestions based on coverage analysis.
Analyze existing test suites and source code to suggest additional unit tests that improve test coverage. Use this skill when working with test files and source code to identify untested code paths, missing edge cases, uncovered branches, untested error conditions, and gaps in test coverage. Supports major testing frameworks (pytest, Jest, JUnit, Go testing, etc.) and generates targeted test suggestions based on coverage analysis.
Coverage Enhancer
Analyze existing tests and source code to identify coverage gaps, then suggest specific additional tests to improve overall test coverage and code quality.
Core Capabilities
1. Coverage Gap Analysis
Identify untested areas in source code:
Uncovered lines - Code never executed by tests
Uncovered branches - Conditional paths not tested
Uncovered functions - Methods/functions without tests
Missing error handling tests - Exception paths not verified
Untested edge cases - Boundary conditions not covered
Insufficient scenarios - Limited test diversity
2. Existing Test Analysis
Understand current test coverage by:
Parsing existing test files
Identifying tested functions and methods
Recognizing test patterns and frameworks
Detecting coverage tools in use
Analyzing test quality and completeness
3. Test Suggestion Generation
Generate specific, actionable test recommendations:
defprocess(value):
if value < 0: # Branch 1raise ValueError
elif value == 0: # Branch 2returnNoneelse: # Branch 3return value * 2
Find untested branches:
If/else conditions not covered
Switch/case statements
Exception handlers (try/except/finally)
Early returns
Loop edge cases (zero iterations, one iteration, many)
Identify uncovered functions:
Helper functions without tests
Private methods (if testing them is valuable)
Class methods and properties
Static/class methods
Step 3: Prioritize Coverage Gaps
Focus on high-value additions:
Priority 1: Critical paths
Error handling and validation
Security-sensitive code
Data integrity operations
Public API methods
Priority 2: Complex logic
Conditional logic with multiple branches
Loops with edge cases
State transitions
Algorithm implementations
Priority 3: Completeness
Untested helper functions
Missing edge cases
Property getters/setters
Simple utility functions
Step 4: Generate Test Suggestions
Create specific, ready-to-use tests:
Format:
# Suggested test for uncovered branch: negative input validationdeftest_process_negative_input():
"""Test that negative values raise ValueError."""with pytest.raises(ValueError):
process(-1)
# Reason: This tests the value < 0 branch which is currently uncovered# Coverage impact: +5 lines, +1 branch
Include:
Test name (descriptive)
Test implementation (complete code)
Explanation of what's being tested
Coverage impact estimate
Integration notes (where to add in test file)
Step 5: Suggest Coverage Tool Integration
Recommend running coverage analysis:
# Python
pytest --cov=mymodule --cov-report=html
# JavaScript
npm test -- --coverage
# Java
mvn test jacoco:report
# Go
go test -coverprofile=coverage.out
go tool cover -html=coverage.out
deftest_find_max_empty():
"""Test that empty list returns None."""assert find_max([]) isNone# Coverage: Tests the 'if not numbers' branchdeftest_find_max_single_element():
"""Test with single element (zero loop iterations)."""assert find_max([42]) == 42# Coverage: Tests loop with zero iterationsdeftest_find_max_all_equal():
"""Test with all identical elements."""assert find_max([5, 5, 5, 5]) == 5# Coverage: Tests loop where condition never truedeftest_find_max_negative_numbers():
"""Test with negative numbers."""assert find_max([-5, -1, -10, -3]) == -1# Coverage: Edge case for comparison logic
Pattern 4: Error Handler Coverage
Uncovered code:
defload_config(filename):
try:
withopen(filename) as f:
return json.load(f)
except FileNotFoundError:
return {}
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON in {filename}: {e}")
except Exception as e:
raise RuntimeError(f"Unexpected error loading {filename}: {e}")
# Look for:# - Missing lines (shown in report)# - Uncovered branches (with --cov-branch)# - Files with low coverage (<80%)
Suggest tests based on missing lines
JavaScript (Jest)
Run coverage:
npm test -- --coverage --verbose
Read coverage output:
// coverage/lcov-report/index.html shows:// - Uncovered lines (highlighted in red)// - Uncovered branches// - Function coverage
Java (JaCoCo)
Run coverage:
mvn test jacoco:report
Read report:
target/site/jacoco/index.html
Go
Run coverage:
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
Test Suggestion Template
When suggesting tests, use this format:
## Coverage Gap: [Description]
**Location:** [file:line or function name]
**Current Coverage:** [X%]
**Impact:** +[N] lines, +[M] branches
### Suggested Test:
[Complete test code]
**Explanation:**
[What this test covers and why it's important]
**Where to add:**
[In which test file, near which existing test]
Example:
## Coverage Gap: Error handling for invalid input
**Location:** src/validator.py:45-48
**Current Coverage:** 60% (missing exception path)
**Impact:** +3 lines, +1 branch
### Suggested Test:
```python
def test_validate_email_invalid_format():
"""Test that invalid email format raises ValueError."""
with pytest.raises(ValueError, match="Invalid email format"):
validate_email("not-an-email")
# Additional invalid cases
with pytest.raises(ValueError):
validate_email("")
with pytest.raises(ValueError):
validate_email("@example.com")
Explanation:
This test covers the exception path when email validation fails.
Currently, only the happy path (valid emails) is tested.
This improves branch coverage and ensures proper error messages.
Where to add:
In tests/test_validator.py, after test_validate_email_valid
## Best Practices
1. **Start with existing tests** - Always read current tests first to understand patterns
2. **Match the style** - Use same framework, naming, and structure as existing tests
3. **Focus on value** - Prioritize high-impact coverage gaps over achieving 100%
4. **Test behavior, not implementation** - Focus on what the code does, not how
5. **Keep tests isolated** - Each test should be independent
6. **Use descriptive names** - Test names should explain what's being verified
7. **Add explanations** - Comment why each test is needed for coverage
8. **Suggest coverage tools** - Help users measure and track coverage
9. **Consider mutation testing** - Suggest tests that would catch actual bugs
10. **Balance coverage and maintainability** - Don't over-test trivial code
## Common Coverage Gaps
### Gap 1: Error Cases Not Tested
```python
# Often only happy path is tested
def parse_int(s):
return int(s) # ValueError not tested
# Suggest:
def test_parse_int_invalid():
with pytest.raises(ValueError):
parse_int("not a number")
Gap 2: Edge Cases Missing
# Common values tested, boundaries ignoreddefclamp(value, min_val, max_val):
returnmax(min_val, min(max_val, value))
# Need tests for:# - value == min_val# - value == max_val# - value < min_val# - value > max_val
Gap 3: Else Branches Untested
if condition:
# Tested
do_something()
else:
# Never tested!
do_other()
Gap 4: Loop Edge Cases
for item in collection:
process(item)
# Need tests for:# - Empty collection# - Single item# - Many items
Gap 5: Cleanup/Finally Not Tested
try:
risky_operation()
finally:
cleanup() # Often not verified# Suggest test that verifies cleanup happens
Language-Specific Patterns
For language-specific coverage patterns and testing approaches: