test-and-fix
Run tests and automatically fix common issues
mkdir -p ~/.claude/commands && curl -fsSL https://raw.githubusercontent.com/solanabr/solana-ai-kit/HEAD/.claude/commands/test-and-fix.md -o ~/.claude/commands/test-and-fix.mdtest-and-fix.md
You are running tests and fixing any issues found. This command iteratively tests, diagnoses problems, fixes them, and retests.
## Related Skills
- [testing.md](../skills/testing.md) - Testing strategy details
- [security.md](../skills/security.md) - Security fix patterns
## Overview
This command follows a **test → diagnose → fix → retest** loop until all tests pass or manual intervention is needed.
## Step 1: Initial Test Run
```bash
echo "🧪 Running initial tests..."
# Determine project type and run appropriate tests
if [ -f "Anchor.toml" ]; then
# Anchor project
anchor build && anchor test --skip-deploy
TEST_STATUS=$?
elif grep -q "solana-program" Cargo.toml 2>/dev/null; then
# Native Solana program
cargo build-sbf && cargo test
TEST_STATUS=$?
else
# Standard Rust or backend
cargo test
TEST_STATUS=$?
fi
if [ $TEST_STATUS -eq 0 ]; then
echo "✅ All tests passed!"
exit 0
fi
echo "❌ Tests failed. Starting diagnosis..."
```
## Step 2: Diagnose Issues
Analyze the test output to categorize failures:
### Common Issue Categories
1. **Format Issues**
- Code not formatted
- Inconsistent style
2. **Clippy Warnings**
- Lints not satisfied
- Potential bugs
3. **Compilation Errors**
- Syntax errors
- Type mismatches
- Missing imports
4. **Test Failures**
- Failed assertions
- Logic errors
- Account validation failures (Solana)
5. **Runtime Errors**
- Panics
- Arithmetic overflow
- Account errors (Solana)
## Step 3: Automatic Fixes
### Fix Format Issues
```bash
# Always start with formatting
echo "📝 Fixing format issues..."
cargo fmt
# For TypeScript tests
if [ -d "tests" ] && ls tests/*.ts >/dev/null 2>&1; then
npx prettier --write "tests/**/*.ts"
fi
echo "✅ Format fixed"
```
### Fix Clippy Warnings (Auto-fixable)
```bash
echo "🔧 Fixing clippy warnings..."
# Apply automatic clippy fixes
cargo clippy --fix --allow-dirty --allow-staged
# Note: Not all clippy warnings are auto-fixable
# Manual fixes may be needed for:
# - Logic issues
# - Unsafe code
# - Complex refactorings
echo "✅ Clippy auto-fixes applied"
```
### Fix Common Solana Issues
#### Missing Account in Anchor Test
```bash
# If test fails with "Missing account: system_program"
# Add to test accounts:
# systemProgram: anchor.web3.SystemProgram.programId,
```
#### Account Not Mutable
```bash
# If error: "Account not mutable"
# Update account definition to include 'mut':
# #[account(mut)]
```
#### Insufficient Compute Units
```bash
# If error: "Exceeded CU limit"
# Add compute budget instruction in test:
# .preInstructions([
# ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 })
# ])
```
## Step 4: Rerun Tests
```bash
echo "🔄 Retesting after fixes..."
# Run tests again
if [ -f "Anchor.toml" ]; then
anchor test --skip-deploy
TEST_STATUS=$?
elif grep -q "solana-program" Cargo.toml 2>/dev/null; then
cargo test
TEST_STATUS=$?
else
cargo test
TEST_STATUS=$?
fi
if [ $TEST_STATUS -eq 0 ]; then
echo "✅ All tests now pass!"
exit 0
fi
```
## Step 5: Manual Fix Guidance
If automatic fixes didn't resolve all issues, provide guidance:
```bash
echo "⚠️ Manual fixes needed. Analyzing failures..."
# Parse test output for specific errors
# This is where AI assistance helps diagnose complex issues
```
### Solana-Specific Manual Fixes
#### Account Validation Failures
```rust
// Error: "A has_one constraint was violated"
// Fix: Ensure account relationships match constraints
#[account(
mut,
has_one = authority @ ErrorCode::Unauthorized, // authority must match
)]
pub vault: Account<'info, Vault>,
```
#### PDA Derivation Mismatch
```rust
// Error: "Invalid PDA seed"
// Fix: Verify seeds match between program and test
// Program:
seeds = [b"vault", authority.key().as_ref()]
// Test:
const [vaultPda] = PublicKey.findProgramAddressSync(
[Buffer.from("vault"), authority.publicKey.toBuffer()],
programId
);
```
#### Arithmetic Overflow
```rust
// Error: "Arithmetic overflow"
// Fix: Use checked arithmetic
// Bad:
vault.balance = vault.balance + amount;
// Good:
vault.balance = vault
.balance
.checked_add(amount)
.ok_or(ErrorCode::Overflow)?;
```
#### Missing Signer
```rust
// Error: "Missing required signature"
// Fix: Ensure account is marked as Signer
#[account(mut)]
pub authority: Signer<'info>, // Must be Signer, not SystemAccount
```
### Backend Service Manual Fixes
#### Async/Await Issues
```rust
// Error: "Cannot call blocking function in async context"
// Fix: Use async version or spawn_blocking
// Bad:
async fn handler() -> Result<String> {
std::fs::read_to_string("file.txt")? // Blocking!
}
// Good:
async fn handler() -> Result<String> {
tokio::fs::read_to_string("file.txt").await?
}
```
#### Database Connection Issues
```rust
// Error: "Connection pool exhausted"
// Fix: Increase pool size or close connections properly
let pool = PgPoolOptions::new()
.max_connections(50) // Increase if needed
.connect(&database_url)
.await?;
```
## Step 6: Iterative Fixing
```bash
# Maximum fix iterations
MAX_ITERATIONS=5
ITERATION=1
while [ $ITERATION -le $MAX_ITERATIONS ]; do
echo "🔄 Fix iteration $ITERATION/$MAX_ITERATIONS"
# Apply automatic fixes
cargo fmt
cargo clippy --fix --allow-dirty --allow-staged
# Run tests
if [ -f "Anchor.toml" ]; then
anchor test --skip-deploy
else
cargo test
fi
if [ $? -eq 0 ]; then
echo "✅ All tests pass after $ITERATION iteration(s)!"
exit 0
fi
ITERATION=$((ITERATION + 1))
# If still failing after max iterations, need manual intervention
if [ $ITERATION -gt $MAX_ITERATIONS ]; then
echo "⚠️ Maximum iterations reached. Manual fixes required."
echo "Please review the test output above and fix remaining issues."
exit 1
fi
done
```
## Common Fix Patterns
### Pattern 1: Update Test Data
```typeAnchor framework specialist for rapid Solana program development. Use for building programs with Anchor macros, IDL generation, account validation, and standardized patterns. Prioritizes developer experience while maintaining security.\\n\\nUse when: Building new programs quickly, team projects needing standardization, projects requiring IDL for client generation, or when developer experience is prioritized over maximum CU optimization.
DeFi integration specialist for composing with Solana protocols including Jupiter, Drift, Kamino, Raydium, Orca, Meteora, Marginfi, and Sanctum. Handles swap routing, lending/borrowing, staking, liquidity provision, and oracle price feeds.\n\nUse when: Integrating DeFi protocols, building swap interfaces, implementing lending/borrowing, setting up yield strategies, working with Pyth/Switchboard oracles, or composing multi-protocol transactions.
CI/CD, infrastructure, and deployment specialist for Solana projects. Handles GitHub Actions, Docker, monitoring, RPC management, and Cloudflare Workers edge deployment.\n\nUse when: Setting up CI/CD pipelines, containerizing Solana validators or programs, configuring monitoring and alerting, managing RPC infrastructure, deploying edge workers, or automating build and deploy workflows.
Senior Solana game architect for game system design, Unity/C# architecture, on-chain game state, player progression, NFT integration, and PlaySolana ecosystem. Use for high-level game design decisions, architecture reviews, and planning complex game systems.\n\nUse when: Designing new Solana games from scratch, planning game state on-chain, Unity project architecture, integrating with PlaySolana/PSG1, or deciding between implementation approaches.
React Native and Expo specialist for building Solana mobile dApps. Handles mobile wallet adapter integration, transaction signing UX, deep linking, and mobile-specific performance optimization.\n\nUse when: Building React Native or Expo mobile apps with Solana integration, implementing mobile wallet adapter flows, setting up deep links for transaction signing, or optimizing mobile dApp performance.
CU optimization specialist using Pinocchio framework. Use for performance-critical programs requiring 80-95% CU reduction vs Anchor. Specializes in zero-copy access, manual validation, and minimal binary size.\\n\\nUse when: CU limits are being hit, transaction costs are significant at scale, binary size must be minimized, or maximum throughput is required.
Rust backend specialist for building async services that interact with Solana blockchain. Builds APIs, indexing services, and off-chain processing using Axum, Tokio, and modern async patterns.\n\nUse when: Building REST/WebSocket APIs for Solana dApps, implementing transaction indexers, creating webhook services, or any Rust backend that interacts with Solana.
Senior Solana program architect for system design, account structures, PDA schemes, token economics, and cross-program composability. Use for high-level design decisions, architecture reviews, and planning complex multi-program systems.\n\nUse when: Designing new programs from scratch, planning account structures, optimizing PDA schemes, reviewing architecture for security, or deciding between implementation approaches.