rust-testing
Rust testing patterns including unit tests, integration tests, async testing, property-based testing, mocking, and coverage. Follows TDD methodology.
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
- Hedef kodu tanımla — Test edilecek fonksiyon, trait veya modülü bul
- Bir test yaz —
#[cfg(test)]modülünde#[test]kullan, parametreli testler için rstest veya property-based testler için proptest - Bağımlılıkları mock'la — Test altındaki birimi izole etmek için mockall kullan
- Testleri çalıştır (RED) — Testin beklenen hata ile başarısız olduğunu doğrula
- Uygula (GREEN) — Geçmek için minimal kod yaz
- Refactor — Testleri yeşil tutarken iyileştir
- 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 etRust'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 REFACTORUnit 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ırmaHata 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.rsEntegrasyon 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评论
