← 返回列表
全部 Skill›测试与安全 Testing & Security›rust-testing

rust-testing

作者 @affaan-m · 语言 tur
Rust testing patterns including unit tests, integration tests, async testing, property-based testing, mocking, and coverage. Follows TDD methodology.
测试与安全 Testing & Security测试通用执行命令待翻译
存储库
最近源活动
2026-11-20 09:13
检测 SKILL.md 语言
tur
星标 ★
307,331
分支 Fork
45,351
安装选项
提示
指令
使用 AI 助手安装
将下面的提示复制到你正在使用的 AI 助手中。
下载完整 Skill 目录(含全部配套文件)。 下载压缩包 ↓
SKILL.md 原文预览

Rust Test Desenleri

TDD metodolojisini takip ederek güvenilir, bakım yapılabilir testler yazmak için kapsamlı Rust test desenleri.

Ne Zaman Kullanılır

  • Yeni Rust fonksiyonları, metotları veya trait'leri yazma
  • Mevcut koda test kapsamı ekleme
  • Performans-kritik kod için benchmark'lar oluşturma
  • Girdi doğrulama için property-based testler uygulama
  • Rust projelerinde TDD iş akışını takip etme

Nasıl Çalışır

  1. Hedef kodu tanımla — Test edilecek fonksiyon, trait veya modülü bul
  2. Bir test yaz — #[cfg(test)] modülünde #[test] kullan, parametreli testler için rstest veya property-based testler için proptest
  3. Bağımlılıkları mock'la — Test altındaki birimi izole etmek için mockall kullan
  4. Testleri çalıştır (RED) — Testin beklenen hata ile başarısız olduğunu doğrula
  5. Uygula (GREEN) — Geçmek için minimal kod yaz
  6. Refactor — Testleri yeşil tutarken iyileştir
  7. Kapsamı kontrol et — cargo-llvm-cov kullan, 80%+ hedefle

Rust için TDD İş Akışı

RED-GREEN-REFACTOR Döngüsü

RED     → Önce başarısız bir test yaz
GREEN   → Testi geçmek için minimal kod yaz
REFACTOR → Testleri yeşil tutarken kodu iyileştir
REPEAT  → Bir sonraki gereksinimle devam et

Rust'ta Adım-Adım TDD

// RED: Önce testi yaz, yer tutucu olarak todo!() kullan
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 → 'not yet implemented'da panic
// GREEN: todo!()'yu minimal implementasyonla değiştir
pub fn add(a: i32, b: i32) -> i32 { a + b }
// cargo test → GEÇTİ, sonra testleri yeşil tutarken REFACTOR

Unit Testler

Modül Seviyesi Test Organizasyonu

// 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!("invalid email: {email}"));
        }
        Ok(Self { name: name.into(), email })
    }

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

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

    #[test]
    fn creates_user_with_valid_email() {
        let user = User::new("Alice", "alice@example.com").unwrap();
        assert_eq!(user.display_name(), "Alice");
        assert_eq!(user.email, "alice@example.com");
    }

    #[test]
    fn rejects_invalid_email() {
        let result = User::new("Bob", "not-an-email");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("invalid email"));
    }
}

Assertion Makroları

assert_eq!(2 + 2, 4);                                    // Eşitlik
assert_ne!(2 + 2, 5);                                    // Eşitsizlik
assert!(vec![1, 2, 3].contains(&2));                     // Boolean
assert_eq!(value, 42, "expected 42 but got {value}");    // Özel mesaj
assert!((0.1_f64 + 0.2 - 0.3).abs() < f64::EPSILON);   // Float karşılaştırma

Hata ve Panic Testi

Result Dönüşlerini Test Etme

#[test]
fn parse_returns_error_for_invalid_input() {
    let result = parse_config("}{invalid");
    assert!(result.is_err());

    // Spesifik hata varyantını doğrula
    let err = result.unwrap_err();
    assert!(matches!(err, ConfigError::ParseError(_)));
}

#[test]
fn parse_succeeds_for_valid_input() -> Result<(), Box<dyn std::error::Error>> {
    let config = parse_config(r#"{"port": 8080}"#)?;
    assert_eq!(config.port, 8080);
    Ok(()) // Herhangi bir ? Err döndürürse test başarısız olur
}

Panic'leri Test Etme

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

#[test]
#[should_panic(expected = "index out of bounds")]
fn panics_with_specific_message() {
    let v: Vec<i32> = vec![];
    let _ = v[0];
}

Entegrasyon Testleri

Dosya Yapısı

my_crate/
├── src/
│   └── lib.rs
├── tests/              # Entegrasyon testleri
│   ├── api_test.rs     # Her dosya ayrı bir test binary'si
│   ├── db_test.rs
│   └── common/         # Paylaşılan test yardımcıları
│       └── mod.rs

Entegrasyon Testleri Yazma

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

#[test]
fn full_request_lifecycle() {
    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");
}

Async Testler

Tokio ile

#[tokio::test]
async fn fetches_data_successfully() {
    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 handles_timeout() {
    use std::time::Duration;
    let result = tokio::time::timeout(
        Duration::from_millis(100),
        slow_operation(),
    ).await;

    assert!(result.is_err(), "should have timed out");
}

Test Organizasyon Desenleri

rstest ile Parametreli Testler

use rstest::{rstest, fixture};

#[rstest]
#[case("hello", 5)]
#[case("", 0)]
#[case("rust", 4)]
fn test_string_length(#[case] input: &str, #[case] expected: usize) {
    assert_eq!(input.len(), expected);
}

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

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

Test Yardımcıları

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

    /// Mantıklı varsayılanlarla test kullanıcısı oluşturur.
    fn make_user(name: &str) -> User {
        User::new(name, &format!("{name}@test.com")).unwra
评论
Aaffaan-m
affaan-m
affaan-m/ECC
查看 GitHub 仓库 查看作者的其他 Skill
来源信息
作者@affaan-m
所属大类测试与安全 Testing & Security / 测试
国内可用性通用
最近源活动2026-11-20 09:13
风险提示执行命令
提示:风险标签为程序静态扫描结果,仅作提示,不代表安全认证。安装前请阅读 SKILL.md 及其引用的脚本、权限,自行判断是否可信。