Skip to main content
ClaudeWave
Slash Command65 estrellas del repoactualizado yesterday

test-rust

Run Rust tests for Solana programs and backend services

Instalar en Claude Code
Copiar
mkdir -p ~/.claude/commands && curl -fsSL https://raw.githubusercontent.com/solanabr/solana-ai-kit/HEAD/.claude/commands/test-rust.md -o ~/.claude/commands/test-rust.md
Después abre una sesión nueva de Claude Code; el slash command carga automáticamente.

test-rust.md

You are running Rust tests. This command covers Solana program testing (Mollusk, LiteSVM, Surfpool, Trident) and backend service testing.

## Related Skills

- [testing.md](../skills/testing.md) - Testing strategy details
- [security.md](../skills/security.md) - Security testing checklist
- [programs/anchor.md](../skills/ext/solana-dev/skill/references/programs/anchor.md) - Anchor test patterns
- [programs/pinocchio.md](../skills/ext/solana-dev/skill/references/programs/pinocchio.md) - Pinocchio test patterns

## Step 1: Identify Project Type

```bash
echo "🔍 Detecting project type..."

if [ -f "Anchor.toml" ]; then
    echo "📦 Anchor project detected"
    PROJECT_TYPE="anchor"
elif grep -q "pinocchio" Cargo.toml 2>/dev/null; then
    echo "🎯 Pinocchio program detected"
    PROJECT_TYPE="pinocchio"
elif grep -q "solana-program" Cargo.toml 2>/dev/null; then
    echo "⚙️  Solana native program detected"
    PROJECT_TYPE="solana"
elif grep -q "axum\|tokio" Cargo.toml 2>/dev/null; then
    echo "🌐 Rust backend service detected"
    PROJECT_TYPE="backend"
else
    echo "🦀 Standard Rust project detected"
    PROJECT_TYPE="standard"
fi
```

---

## Solana Program Testing

### Testing Pyramid

1. **Unit tests (fastest)**: Mollusk - individual instruction tests
2. **Integration tests (fast)**: LiteSVM - multi-instruction flows
3. **Realistic state tests**: Surfpool - mainnet/devnet state locally
4. **Fuzz tests**: Trident - edge case discovery

### Mollusk Unit Tests

Fast, isolated tests for individual instructions:

```bash
echo "🐚 Running Mollusk unit tests..."
cargo test --lib -- --nocapture
```

```rust
#[cfg(test)]
mod tests {
    use mollusk_svm::Mollusk;
    use solana_sdk::{account::Account, pubkey::Pubkey, instruction::Instruction};

    #[test]
    fn test_initialize() {
        let program_id = Pubkey::new_unique();
        let mollusk = Mollusk::new(&program_id, "target/deploy/my_program.so");

        // Setup accounts
        let user = Pubkey::new_unique();
        let accounts = vec![
            (user, Account::new(1_000_000_000, 0, &program_id)),
        ];

        // Create instruction
        let instruction = Instruction {
            program_id,
            accounts: vec![],
            data: vec![0], // Initialize discriminator
        };

        // Process and verify
        let result = mollusk.process_instruction(&instruction, &accounts);
        assert!(result.program_result.is_ok());

        // Check CU usage
        println!("CU consumed: {}", result.compute_units_consumed);
        assert!(result.compute_units_consumed < 50_000);
    }
}
```

### LiteSVM Integration Tests

Multi-instruction flow testing:

```bash
echo "⚡ Running LiteSVM integration tests..."
cargo test --test '*'
```

```rust
#[cfg(test)]
mod tests {
    use litesvm::LiteSVM;
    use solana_sdk::{signature::Keypair, signer::Signer, transaction::Transaction};

    #[test]
    fn test_full_deposit_withdraw_flow() {
        let mut svm = LiteSVM::new();

        // Add program
        let program_id = Pubkey::new_unique();
        svm.add_program(program_id, include_bytes!("../target/deploy/my_program.so"));

        // Create and fund user
        let user = Keypair::new();
        svm.airdrop(&user.pubkey(), 10_000_000_000).unwrap();

        // Build transaction
        let tx = Transaction::new_signed_with_payer(
            &[/* deposit instruction */],
            Some(&user.pubkey()),
            &[&user],
            svm.latest_blockhash(),
        );

        // Execute and verify
        let result = svm.send_transaction(tx);
        assert!(result.is_ok());
    }
}
```

### Surfpool Integration Tests

Test against realistic mainnet/devnet state locally:

```bash
echo "🏄 Running Surfpool integration tests..."

# Start local Surfnet (drop-in replacement for test-validator)
surfpool start --background

# Run tests against realistic state
cargo test --test integration

# Stop Surfnet
surfpool stop
```

```typescript
// Surfpool enables:
// - Complex CPIs with mainnet programs (Jupiter 40+ accounts)
// - Time travel and block manipulation
// - Account cloning between environments

// Time travel to specific slot
await connection._rpcRequest('surfnet_timeTravel', [{
    absoluteSlot: 250000000
}]);

// Clone account from mainnet
await connection._rpcRequest('surfnet_cloneProgramAccount', [{
    source: mainnetProgramId.toString(),
    destination: localProgramId.toString(),
    account: accountPubkey.toString(),
}]);
```

### Trident Fuzz Tests

Property-based fuzzing for edge cases:

```bash
echo "🔱 Running Trident fuzz tests..."

# Initialize (first time only)
if [ ! -d "trident-tests" ]; then
    trident init
fi

cd trident-tests

# Run fuzz tests (modern syntax)
trident fuzz run --timeout 300

# Check for crashes
if [ -d "hfuzz_workspace" ]; then
    echo "📋 Checking for crash reports..."
    find hfuzz_workspace -name "crashes" -type d -exec ls -la {} \; 2>/dev/null
fi

cd ..
```

### Complete Solana Test Suite

```bash
echo "🧪 Running complete Solana test suite..."

# 1. Build program
if [ -f "Anchor.toml" ]; then
    anchor build
else
    cargo build-sbf
fi

# 2. Unit tests (Mollusk)
echo "📍 Unit tests..."
cargo test --lib

# 3. Integration tests (LiteSVM)
echo "📍 Integration tests..."
cargo test --test '*'

# 4. Fuzz tests (Trident) - quick run
if [ -d "trident-tests" ]; then
    echo "📍 Fuzz tests..."
    cd trident-tests && trident fuzz run --timeout 60 && cd ..
fi

echo "✅ All Solana tests complete!"
```

---

## Backend Service Testing

### Axum/Tokio Service Tests

```bash
echo "🌐 Running backend service tests..."

# Run all tests
cargo test

# Run with test database
if [ -f ".env.test" ]; then
    export $(cat .env.test | xargs)
fi

# Integration tests (serial to avoid DB conflicts)
cargo test --test '*' -- --test-threads=1
```

### Database Testing Pattern

```rust
#[cfg(test)]
mod tests {
    use sqlx::PgPool;

    #[sqlx::test]
    async fn test_user_creation(poo
anchor-engineerSubagent

Anchor 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-engineerSubagent

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.

devops-engineerSubagent

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.

game-architectSubagent

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.

mobile-engineerSubagent

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.

pinocchio-engineerSubagent

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-engineerSubagent

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.

solana-architectSubagent

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.