go-test-coverage
WHEN: User wants to improve test coverage, find untested code, generate test stubs, or asks "what tests am I missing?" or "how do I improve coverage?" for a Go project. WHEN NOT: When running existing tests, debugging test failures, or benchmarking.
What this skill does
# Go Test Coverage
Test coverage gap analysis and recommendations for Go projects. Identifies missing or insufficient test coverage and generates actionable recommendations.
## What It Does
1. **Coverage Analysis** — Runs `go test -cover` and parses results
2. **Gap Identification** — Finds untested exported functions, error paths, and edge cases
3. **Recommendation Engine** — Suggests specific test cases using table-driven patterns
4. **Stub Generation** — Creates ready-to-use test file stubs
## Steps
### API Integration (Optional)
If `GOPHER_GUIDES_API_KEY` is set, verify it:
```bash
curl -s -H "Authorization: Bearer $GOPHER_GUIDES_API_KEY" \
https://gopherguides.com/api/gopher-ai/me
```
If not set, local analysis tools (go vet, staticcheck, golangci-lint) still provide comprehensive analysis. Set the key for enhanced API-powered insights. Get your key at [gopherguides.com](https://gopherguides.com).
### 1. Measure Current Coverage
```bash
# Generate coverage profile
go test -coverprofile=coverage.out ./...
# View per-function coverage
go tool cover -func=coverage.out
# Generate HTML report (optional)
go tool cover -html=coverage.out -o coverage.html
```
### 2. Identify Gaps
Parse coverage output to find:
- **Untested exported functions** — Any `func` with 0% coverage
- **Partially covered functions** — Functions with branches not hit
- **Untested error paths** — `if err != nil` blocks never executed
- **Missing edge cases** — Boundary conditions not exercised
```bash
# Find functions with 0% coverage
go tool cover -func=coverage.out | grep "0.0%"
# Find exported functions without test files
for f in $(find . -name "*.go" ! -name "*_test.go" -path "*/pkg/*" -o -name "*.go" ! -name "*_test.go" -path "*/internal/*"); do
dir=$(dirname "$f")
base=$(basename "$f" .go)
if [ ! -f "${dir}/${base}_test.go" ]; then
echo "Missing test file: ${dir}/${base}_test.go"
fi
done
```
### 3. Generate Recommendations
For each untested function, recommend:
- **Table-driven tests** for functions with multiple input/output combinations
- **Error path tests** for functions that return errors
- **Edge case tests** for boundary values (nil, empty, zero, max)
- **Integration tests** for functions with external dependencies
### 4. Generate Test Stubs
Create test files with the table-driven pattern:
```go
func TestFunctionName(t *testing.T) {
tests := []struct {
name string
input InputType
want OutputType
wantErr bool
}{
{
name: "valid input",
input: validInput,
want: expectedOutput,
},
{
name: "empty input returns error",
input: emptyInput,
wantErr: true,
},
{
name: "nil input returns error",
input: nil,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got, err := FunctionName(tt.input)
if (err != nil) != tt.wantErr {
t.Errorf("FunctionName() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("FunctionName() = %v, want %v", got, tt.want)
}
})
}
}
```
## Output Format
```markdown
## Test Coverage Report
**Project:** {name}
**Current Coverage:** {percent}%
**Target Coverage:** 80%
### Coverage by Package
| Package | Coverage | Status |
|---------|----------|--------|
| pkg/auth | 85% | ✅ |
| pkg/api | 45% | ⚠️ |
| internal/db | 20% | 🔴 |
### Untested Exported Functions
| Function | File | Priority |
|----------|------|----------|
| `HandleLogin` | pkg/auth/handler.go | High |
| `ValidateToken` | pkg/auth/token.go | High |
| `FormatResponse` | pkg/api/response.go | Medium |
### Recommended Test Cases
#### `HandleLogin` (pkg/auth/handler.go)
1. Valid credentials → successful login
2. Invalid password → 401 error
3. Missing username → validation error
4. Expired account → forbidden error
5. Rate limited → 429 error
### Generated Stubs
Test stubs have been written to:
- `pkg/auth/handler_test.go`
- `pkg/api/response_test.go`
```
## Helper Script
After installation via `install.sh`, scripts are at `.github/skills/scripts/`. Run the coverage report script for a formatted summary with gap analysis:
```bash
bash .github/skills/scripts/coverage-report.sh [minimum-coverage-percent]
```
Default minimum is 80%. Configure thresholds in severity configuration at the installed path:
```yaml
coverage:
minimum: 80
per_package_minimum: 60
below_threshold_severity: warning
```
## Gopher Guides API Integration
> **Note:** API calls send source code to gopherguides.com for analysis. Ensure your organization's policy permits external code analysis.
For full API usage examples, see [API Usage Reference](../references/api-usage.md).
## References
- Existing gopher-ai command: `plugins/go-dev/commands/test-gen.md`
- Go skill: `plugins/go-dev/skills/go/`
- [Go Testing](https://go.dev/doc/tutorial/add-a-test)
---
*Powered by [Gopher Guides](https://gopherguides.com) training materials.*
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.