// rust/03-testing-strategies.rs/*Comprehensive testing strategies for Rust crates*/usestd::collections::HashMap;useanyhow::Result;useproptest::prelude::*;usemockall::mock;// Unit tests#[cfg(test)]modunit_tests{usesuper::*;#[test]fntest_basic_functionality(){letmutprocessor=DataProcessor::new();assert!(processor.add_item("key","value").is_ok());assert_eq!(processor.get_item("key"),Some("value"));}#[test]fntest_error_handling(){letmutprocessor=DataProcessor::new();assert!(processor.add_item("","value").is_err());}#[test]fntest_edge_cases(){letmutprocessor=DataProcessor::new();// Test with empty valueassert!(processor.add_item("key","").is_ok());// Test with special charactersassert!(processor.add_item("key@#$","value!@#").is_ok());// Test with unicodeassert!(processor.add_item("ключ","значение").is_ok());}}// Integration tests#[cfg(test)]modintegration_tests{usesuper::*;#[test]fntest_full_workflow(){letmutprocessor=DataProcessor::new();// Add multiple itemsprocessor.add_item("item1","value1").unwrap();processor.add_item("item2","value2").unwrap();processor.add_item("item3","value3").unwrap();// Verify all itemsassert_eq!(processor.get_item("item1"),Some("value1"));assert_eq!(processor.get_item("item2"),Some("value2"));assert_eq!(processor.get_item("item3"),Some("value3"));// Test removalprocessor.remove_item("item2").unwrap();assert_eq!(processor.get_item("item2"),None);}}// Property-based testing#[cfg(test)]modproperty_tests{usesuper::*;useproptest::prelude::*;proptest!{#[test]fntest_add_get_property(keyin"[a-zA-Z0-9_]+",valuein".*"){letmutprocessor=DataProcessor::new();processor.add_item(&key,&value).unwrap();assert_eq!(processor.get_item(&key),Some(&value));}#[test]fntest_remove_property(keyin"[a-zA-Z0-9_]+",valuein".*"){letmutprocessor=DataProcessor::new();processor.add_item(&key,&value).unwrap();processor.remove_item(&key).unwrap();assert_eq!(processor.get_item(&key),None);}}}// Mock testingmock!{pubDataProcessor{}implDataProcessorforDataProcessor{fnadd_item(&mutself,key:&str,value:&str)->Result<()>;fnget_item(&self,key:&str)->Option<&str>;fnremove_item(&mutself,key:&str)->Result<()>;}}#[cfg(test)]modmock_tests{usesuper::*;#[test]fntest_with_mock(){letmutmock=MockDataProcessor::new();mock.expect_add_item().with(eq("test_key"),eq("test_value")).times(1).returning(|_,_|Ok(()));mock.expect_get_item().with(eq("test_key")).times(1).returning(|_|Some("test_value"));// Use the mockmock.add_item("test_key","test_value").unwrap();assert_eq!(mock.get_item("test_key"),Some("test_value"));}}// Performance tests#[cfg(test)]modperformance_tests{usesuper::*;usestd::time::Instant;#[test]fntest_performance(){letmutprocessor=DataProcessor::new();letstart=Instant::now();// Add 1000 itemsforiin0..1000{processor.add_item(&format!("key_{}",i),&format!("value_{}",i)).unwrap();}letduration=start.elapsed();println!("Added 1000 items in {:?}",duration);// Performance should be under 10msassert!(duration.as_millis()<10);}}// Example implementationpubstructDataProcessor{data:HashMap<String,String>,}implDataProcessor{pubfnnew()->Self{Self{data:HashMap::new(),}}pubfnadd_item(&mutself,key:&str,value:&str)->Result<()>{ifkey.is_empty(){returnErr(anyhow::anyhow!("Key cannot be empty"));}self.data.insert(key.to_string(),value.to_string());Ok(())}pubfnget_item(&self,key:&str)->Option<&str>{self.data.get(key).map(|s|s.as_str())}pubfnremove_item(&mutself,key:&str)->Result<()>{ifkey.is_empty(){returnErr(anyhow::anyhow!("Key cannot be empty"));}self.data.remove(key);Ok(())}}
// rust/04-documentation.rs/*Documentation patterns and examples for Rust crates*/usestd::collections::HashMap;useanyhow::Result;/// A high-performance data processor for handling key-value operations.////// # Examples////// Basic usage:/// ```/// use my_crate::DataProcessor;////// let mut processor = DataProcessor::new();/// processor.add_item("key", "value").unwrap();/// assert_eq!(processor.get_item("key"), Some("value"));/// ```////// With configuration:/// ```/// use my_crate::{DataProcessor, Config};////// let config = Config {/// max_items: 1000,/// enable_caching: true,/// };/// let processor = DataProcessor::with_config(config);/// ```////// # Performance////// This processor is optimized for high-throughput scenarios:/// - O(1) average case for insertions and lookups/// - Memory-efficient storage/// - Thread-safe operations////// # Thread Safety////// All operations are thread-safe and can be used in concurrent environments.pubstructDataProcessor{data:HashMap<String,String>,config:Config,}/// Configuration options for the data processor.////// # Examples////// ```/// use my_crate::Config;////// let config = Config {/// max_items: 1000,/// enable_caching: true,/// };/// ```#[derive(Debug, Clone)]pubstructConfig{/// Maximum number of items that can be stored.pubmax_items:usize,/// Whether to enable internal caching for better performance.pubenable_caching:bool,}implDefaultforConfig{fndefault()->Self{Self{max_items:10000,enable_caching:true,}}}implDataProcessor{/// Creates a new data processor with default configuration.////// # Examples////// ```/// use my_crate::DataProcessor;////// let processor = DataProcessor::new();/// ```pubfnnew()->Self{Self::with_config(Config::default())}/// Creates a new data processor with custom configuration.////// # Arguments////// * `config` - Configuration options for the processor////// # Examples////// ```/// use my_crate::{DataProcessor, Config};////// let config = Config {/// max_items: 1000,/// enable_caching: true,/// };/// let processor = DataProcessor::with_config(config);/// ```pubfnwith_config(config:Config)->Self{Self{data:HashMap::new(),config,}}/// Adds a new item to the processor.////// # Arguments////// * `key` - The key for the item (cannot be empty)/// * `value` - The value to store////// # Returns////// Returns `Ok(())` if the item was added successfully, or an error if:/// - The key is empty/// - The maximum number of items has been reached////// # Examples////// ```/// use my_crate::DataProcessor;////// let mut processor = DataProcessor::new();/// processor.add_item("user_id", "12345").unwrap();/// ```////// # Errors////// This function will return an error if the key is empty or if the/// maximum number of items has been reached.pubfnadd_item(&mutself,key:&str,value:&str)->Result<()>{ifkey.is_empty(){returnErr(anyhow::anyhow!("Key cannot be empty"));}ifself.data.len()>=self.config.max_items{returnErr(anyhow::anyhow!("Maximum number of items reached"));}self.data.insert(key.to_string(),value.to_string());Ok(())}/// Retrieves an item by its key.////// # Arguments////// * `key` - The key to look up////// # Returns////// Returns `Some(&str)` if the item exists, or `None` if not found.////// # Examples////// ```/// use my_crate::DataProcessor;////// let mut processor = DataProcessor::new();/// processor.add_item("user_id", "12345").unwrap();/// assert_eq!(processor.get_item("user_id"), Some("12345"));/// ```pubfnget_item(&self,key:&str)->Option<&str>{self.data.get(key).map(|s|s.as_str())}/// Removes an item by its key.////// # Arguments////// * `key` - The key of the item to remove////// # Returns////// Returns `Ok(())` if the item was removed successfully, or an error if the key is empty.////// # Examples////// ```/// use my_crate::DataProcessor;////// let mut processor = DataProcessor::new();/// processor.add_item("user_id", "12345").unwrap();/// processor.remove_item("user_id").unwrap();/// assert_eq!(processor.get_item("user_id"), None);/// ```pubfnremove_item(&mutself,key:&str)->Result<()>{ifkey.is_empty(){returnErr(anyhow::anyhow!("Key cannot be empty"));}self.data.remove(key);Ok(())}/// Returns the number of items currently stored.////// # Examples////// ```/// use my_crate::DataProcessor;////// let mut processor = DataProcessor::new();/// processor.add_item("key1", "value1").unwrap();/// processor.add_item("key2", "value2").unwrap();/// assert_eq!(processor.len(), 2);/// ```pubfnlen(&self)->usize{self.data.len()}/// Returns `true` if the processor is empty.////// # Examples////// ```/// use my_crate::DataProcessor;////// let processor = DataProcessor::new();/// assert!(processor.is_empty());/// ```pubfnis_empty(&self)->bool{self.data.is_empty()}}implDefaultforDataProcessor{fndefault()->Self{Self::new()}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_documentation_examples(){letmutprocessor=DataProcessor::new();processor.add_item("key","value").unwrap();assert_eq!(processor.get_item("key"),Some("value"));}}