Communitygithub.com

Testes Rust

Padrões de teste em Rust incluindo testes unitários, testes de integração, testes assíncronos, testes baseados em propriedades, mocks e cobertura. Segue a metodologia TDD. Use ao escrever testes Rust — unitários, integração, assíncronos, baseados em propriedades ou cobertura.

O que é Testes Rust?

Esta habilidade fornece um guia abrangente de padrões de teste em Rust, seguindo a metodologia TDD (Test-Driven Development). Ela cobre todo o ciclo RED-GREEN-REFACTOR, desde a escrita de testes que falham (RED), implementação mínima (GREEN) e refatoração, até a verificação de cobertura. A habilidade é útil para desenvolvedores que desejam escrever testes confiáveis e de fácil manutenção em projetos Rust, sejam eles bibliotecas, aplicações web ou ferramentas de linha de comando. O conteúdo inclui exemplos práticos de testes unitários com módulos `#[cfg(test)]`, testes de integração, testes assíncronos com Tokio, testes parametrizados com `rstest`, testes baseados em propriedades com `proptest`, mocks com `mockall`, documentação executável via doc tests, benchmarks com Criterion e configuração de cobertura com `cargo-llvm-cov`. Também aborda boas práticas como nomear testes descritivamente, priorizar `assert_eq!` sobre `assert!` e evitar `#[should_panic]` quando possível. A habilidade é compatível com qualquer ambiente Rust (bibliotecas, projetos binários) e se integra facilmente em pipelines CI, como GitHub Actions.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/rust-testing

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Padrões de Teste em Rust

Padrões de teste abrangentes para Rust para escrever testes confiáveis e de fácil manutenção seguindo a metodologia TDD.

Quando Usar

  • Escrevendo novas funções, métodos ou traits em Rust
  • Adicionando cobertura de teste a código existente
  • Criando benchmarks para código crítico de desempenho
  • Implementando testes baseados em propriedades para validação de entrada
  • Seguindo fluxo de trabalho TDD em projetos Rust

Como Funciona

  1. Identifique o código alvo — Encontre a função, trait ou módulo a ser testado
  2. Escreva um teste — Use #[test] em um módulo #[cfg(test)], rstest para testes parametrizados ou proptest para testes baseados em propriedades
  3. Mock de dependências — Use mockall para isolar a unidade sob teste
  4. Execute os testes (RED) — Verifique se o teste falha com o erro esperado
  5. Implemente (GREEN) — Escreva o mínimo de código para passar
  6. Refatore — Melhore enquanto mantém os testes verdes
  7. Verifique a cobertura — Use cargo-llvm-cov, alvo 80%+

Fluxo de Trabalho TDD para Rust

O Ciclo RED-GREEN-REFACTOR

RED     → Escreva um teste com falha primeiro
GREEN   → Escreva o mínimo de código para passar o teste
REFACTOR → Melhore o código enquanto mantém os testes verdes
REPITA  → Continue com o próximo requisito

TDD Passo a Passo em Rust

// RED: Escreva o teste primeiro, use todo!() como placeholder
pub fn add(a: i32, b: i32) -> i32 { todo!() }

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_add() { assert_eq!(add(2, 3), 5); }
}
// cargo test → entra em pânico em 'not yet implemented'
// GREEN: Substitua todo!() pela implementação mínima
pub fn add(a: i32, b: i32) -> i32 { a + b }
// cargo test → PASSOU, então REFATORAR enquanto mantém os testes verdes

Testes Unitários

Organização de Testes no Nível do Módulo

// src/user.rs
pub struct User {
    pub name: String,
    pub email: String,
}

impl User {
    pub fn new(name: impl Into<String>, email: impl Into<String>) -> Result<Self, String> {
        let email = email.into();
        if !email.contains('@') {
            return Err(format!("email inválido: {email}"));
        }
        Ok(Self { name: name.into(), email })
    }

    pub fn display_name(&self) -> &str {
        &self.name
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cria_usuario_com_email_valido() {
        let user = User::new("Alice", "[email protected]").unwrap();
        assert_eq!(user.display_name(), "Alice");
        assert_eq!(user.email, "[email protected]");
    }

    #[test]
    fn rejeita_email_invalido() {
        let result = User::new("Bob", "não-é-email");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("email inválido"));
    }
}

Macros de Asserção

assert_eq!(2 + 2, 4);                                    // Igualdade
assert_ne!(2 + 2, 5);                                    // Desigualdade
assert!(vec![1, 2, 3].contains(&2));                     // Booleano
assert_eq!(value, 42, "esperava 42 mas obteve {value}");    // Mensagem personalizada
assert!((0.1_f64 + 0.2 - 0.3).abs() < f64::EPSILON);   // Comparação de ponto flutuante

Testes de Erro e Pânico

Testando Retornos Result

#[test]
fn parse_retorna_erro_para_entrada_invalida() {
    let result = parse_config("}{"inválido);
    assert!(result.is_err());

    // Assert de variante de erro específica
    let err = result.unwrap_err();
    assert!(matches!(err, ConfigError::ParseError(_)));
}

#[test]
fn parse_sucesso_para_entrada_valida() -> Result<(), Box<dyn std::error::Error>> {
    let config = parse_config(r#"{"port": 8080}"#)?;
    assert_eq!(config.port, 8080);
    Ok(()) // Teste falha se algum ? retornar Err
}

Testando Pânicos

#[test]
#[should_panic]
fn panic_para_entrada_vazia() {
    process(&[]);
}

#[test]
#[should_panic(expected = "índice fora dos limites")]
fn panic_com_mensagem_especifica() {
    let v: Vec<i32> = vec![];
    let _ = v[0];
}

Testes de Integração

Estrutura de Arquivos

my_crate/
├── src/
│   └── lib.rs
├── tests/              # Testes de integração
│   ├── api_test.rs     # Cada arquivo é um binário de teste separado
│   ├── db_test.rs
│   └── common/         # Utilitários de teste compartilhados
│       └── mod.rs

Escrevendo Testes de Integração

// tests/api_test.rs
use my_crate::{App, Config};

#[test]
fn ciclo_de_vida_completo_da_requisicao() {
    let config = Config::test_default();
    let app = App::new(config);

    let response = app.handle_request("/health");
    assert_eq!(response.status, 200);
    assert_eq!(response.body, "OK");
}

Testes Assíncronos

Com Tokio

#[tokio::test]
async fn busca_dados_com_sucesso() {
    let client = TestClient::new().await;
    let result = client.get("/data").await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap().items.len(), 3);
}

#[tokio::test]
async fn lida_com_timeout() {
    use std::time::Duration;
    let result = tokio::time::timeout(
        Duration::from_millis(100),
        operacao_lenta(),
    ).await;

    assert!(result.is_err(), "deveria ter excedido o tempo limite");
}

Padrões de Organização de Testes

Testes Parametrizados com rstest

use rstest::{rstest, fixture};

#[rstest]
#[case("olá", 3)]
#[case("", 0)]
#[case("rust", 4)]
fn test_comprimento_string(#[case] input: &str, #[case] expected: usize) {
    assert_eq!(input.len(), expected);
}

// Fixtures
#[fixture]
fn test_db() -> TestDb {
    TestDb::new_in_memory()
}

#[rstest]
fn test_insert(test_db: TestDb) {
    test_db.insert("chave", "valor");
    assert_eq!(test_db.get("chave"), Some("valor".into()));
}

Helpers de Teste

#[cfg(test)]
mod tests {
    use super::*;

    /// Cria um usuário de teste com valores padrão sensíveis.
    fn make_user(name: &str) -> User {
        User::new(name, &format!("{name}@test.com")).unwrap()
    }

    #[test]
    fn exibicao_usuario() {
        let user = make_user("alice");
        assert_eq!(user.display_name(), "alice");
    }
}

Testes Baseados em Propriedades com proptest

Testes de Propriedade Básicos

use proptest::prelude::*;

proptest! {
    #[test]
    fn ida_e_volta_codificacao_decodificacao(input in ".*") {
        let encoded = encode(&input);
        let decoded = decode(&encoded).unwrap();
        assert_eq!(input, decoded);
    }

    #[test]
    fn ordenacao_preserva_tamanho(mut vec in prop::collection::vec(any::<i32>(), 0..100)) {
        let original_len = vec.len();
        vec.sort();
        assert_eq!(vec.len(), original_len);
    }

    #[test]
    fn ordenacao_produz_saida_ordenada(mut vec in prop::collection::vec(any::<i32>(), 0..100)) {
        vec.sort();
        for window in vec.windows(2) {
            assert!(window[0] <= window[1]);
        }
    }
}

Estratégias Personalizadas

use proptest::prelude::*;

fn email_valido() -> impl Strategy<Value = String> {
    ("[a-z]{1,10}", "[a-z]{1,5}")
        .prop_map(|(user, domain)| format!("{user}@{domain}.com"))
}

proptest! {
    #[test]
    fn aceita_emails_validos(email in email_valido()) {
        assert!(User::new("Test", &email).is_ok());
    }
}

Mocks com mockall

Mocks Baseados em Traits

use mockall::{automock, predicate::eq};

#[automock]
trait UserRepository {
    fn find_by_id(&self, id: u64) -> Option<User>;
    fn save(&self, user: &User) -> Result<(), StorageError>;
}

#[test]
fn servico_retorna_usuario_quando_encontrado() {
    let mut mock = MockUserRepository::new();
    mock.expect_find_by_id()
        .with(eq(42))
        .times(1)
        .returning(|_| Some(User { id: 42, name: "Alice".into() }));

    let service = UserService::new(Box::new(mock));
    let user = service.get_user(42).unwrap();
    assert_eq!(user.name, "Alice");
}

#[test]
fn servico_retorna_none_quando_nao_encontrado() {
    let mut mock = MockUserRepository::new();
    mock.expect_find_by_id()
        .returning(|_| None);

    let service = UserService::new(Box::new(mock));
    assert!(service.get_user(99).is_none());
}

Testes de Documentação

Documentação Executável

/// Soma dois números.
///
/// # Exemplos
///
/// ```
/// use my_crate::add;
///
/// assert_eq!(add(2, 3), 5);
/// assert_eq!(add(-1, 1), 0);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

/// Analisa uma string de configuração.
///
/// # Erros
///
/// Retorna `Err` se a entrada não for TOML válido.
///
/// ```no_run
/// use my_crate::parse_config;
///
/// let config = parse_config(r#"port = 8080"#).unwrap();
/// assert_eq!(config.port, 8080);
/// ```
///
/// ```no_run
/// use my_crate::parse_config;
///
/// assert!(parse_config("}{"inválido).is_err());
/// ```
pub fn parse_config(input: &str) -> Result<Config, ParseError> {
    todo!()
}

Benchmarking com Criterion

# Cargo.toml
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }

[[bench]]
name = "benchmark"
harness = false
// benches/benchmark.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn fibonacci(n: u64) -> u64 {
    match n {
        0 | 1 => n,
        _ => fibonacci(n - 1) + fibonacci(n - 2),
    }
}

fn bench_fibonacci(c: &mut Criterion) {
    c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}

criterion_group!(benches, bench_fibonacci);
criterion_main!(benches);

Cobertura de Testes

Executando Cobertura

# Instalação: cargo install cargo-llvm-cov (ou use taiki-e/install-action no CI)
cargo llvm-cov                    # Resumo
cargo llvm-cov --html             # Relatório HTML
cargo llvm-cov --lcov > lcov.info # Formato LCOV para CI
cargo llvm-cov --fail-under-lines 80  # Falha se abaixo do limiar

Metas de Cobertura

Tipo de CódigoMeta
Lógica de negócio crítica100%
API pública90%+
Código geral80%+
Bindings gerados / FFIExcluir

Comandos de Teste

cargo test                        # Executa todos os testes
cargo test -- --nocapture         # Mostra saída do println
cargo test nome_teste             # Executa testes que correspondem ao padrão
cargo test --lib                  # Apenas testes unitários
cargo test --test api_test        # Apenas testes de integração
cargo test --doc                  # Apenas testes de documentação
cargo test --no-fail-fast         # Não para na primeira falha
cargo test -- --ignored           # Executa testes ignorados

Boas Práticas

FAÇA:

  • Escreva testes PRIMEIRO (TDD)
  • Use módulos #[cfg(test)] para testes unitários
  • Teste comportamento, não implementação
  • Use nomes de teste descritivos que expliquem o cenário
  • Prefira assert_eq! em vez de assert! para melhores mensagens de erro
  • Use ? em testes que retornam Result para saída de erro mais limpa
  • Mantenha os testes independentes — sem estado mutável compartilhado

NÃO FAÇA:

  • Use #[should_panic] quando você puder testar Result::is_err()
  • Mock de tudo — prefira testes de integração quando viável
  • Ignore testes instáveis — corrija ou coloque-os em quarentena
  • Use sleep() em testes — use canais, barreiras ou tokio::time::pause()
  • Pule teste de caminhos de erro

Integração com CI

# GitHub Actions
test:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v4
    - uses: dtolnay/rust-toolchain@stable
      with:
        components: clippy, rustfmt

    - name: Verificar formatação
      run: cargo fmt --check

    - name: Clippy
      run: cargo clippy -- -D warnings

    - name: Executar testes
      run: cargo test

    - uses: taiki-e/install-action@cargo-llvm-cov

    - name: Cobertura
      run: cargo llvm-cov --fail-under-lines 80

Lembre-se: Testes são documentação. Eles mostram como seu código deve ser usado. Escreva-os claramente e mantenha-os atualizados.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

Habilidades Relacionadas