mirror of
https://github.com/rustfs/rustfs.git
synced 2026-08-20 19:42:17 +00:00
Merge branch 'main' of github.com:rustfs/s3-rustfs into feature/observability-metrics
# Conflicts: # Cargo.toml # iam/src/manager.rs # iam/src/store/object.rs # rustfs/src/admin/handlers/sts.rs # rustfs/src/main.rs # rustfs/src/storage/ecfs.rs
This commit is contained in:
@@ -89,3 +89,220 @@ pub const DEFAULT_CONSOLE_PORT: u16 = 9002;
|
||||
/// Default address for rustfs console
|
||||
/// This is the default address for rustfs console.
|
||||
pub const DEFAULT_CONSOLE_ADDRESS: &str = concat!(":", DEFAULT_CONSOLE_PORT);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_app_basic_constants() {
|
||||
// Test application basic constants
|
||||
assert_eq!(APP_NAME, "RustFs");
|
||||
assert!(!APP_NAME.is_empty(), "App name should not be empty");
|
||||
assert!(!APP_NAME.contains(' '), "App name should not contain spaces");
|
||||
|
||||
assert_eq!(VERSION, "0.0.1");
|
||||
assert!(!VERSION.is_empty(), "Version should not be empty");
|
||||
|
||||
assert_eq!(SERVICE_VERSION, "0.0.1");
|
||||
assert_eq!(VERSION, SERVICE_VERSION, "Version and service version should be consistent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_logging_constants() {
|
||||
// Test logging related constants
|
||||
assert_eq!(DEFAULT_LOG_LEVEL, "info");
|
||||
assert!(
|
||||
["trace", "debug", "info", "warn", "error"].contains(&DEFAULT_LOG_LEVEL),
|
||||
"Log level should be a valid tracing level"
|
||||
);
|
||||
|
||||
assert_eq!(USE_STDOUT, true);
|
||||
|
||||
assert_eq!(SAMPLE_RATIO, 1.0);
|
||||
assert!(SAMPLE_RATIO >= 0.0 && SAMPLE_RATIO <= 1.0, "Sample ratio should be between 0.0 and 1.0");
|
||||
|
||||
assert_eq!(METER_INTERVAL, 30);
|
||||
assert!(METER_INTERVAL > 0, "Meter interval should be positive");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_environment_constants() {
|
||||
// Test environment related constants
|
||||
assert_eq!(ENVIRONMENT, "production");
|
||||
assert!(
|
||||
["development", "staging", "production", "test"].contains(&ENVIRONMENT),
|
||||
"Environment should be a standard environment name"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_constants() {
|
||||
// Test connection related constants
|
||||
assert_eq!(MAX_CONNECTIONS, 100);
|
||||
assert!(MAX_CONNECTIONS > 0, "Max connections should be positive");
|
||||
assert!(MAX_CONNECTIONS <= 10000, "Max connections should be reasonable");
|
||||
|
||||
assert_eq!(DEFAULT_TIMEOUT_MS, 3000);
|
||||
assert!(DEFAULT_TIMEOUT_MS > 0, "Timeout should be positive");
|
||||
assert!(DEFAULT_TIMEOUT_MS >= 1000, "Timeout should be at least 1 second");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_security_constants() {
|
||||
// Test security related constants
|
||||
assert_eq!(DEFAULT_ACCESS_KEY, "rustfsadmin");
|
||||
assert!(!DEFAULT_ACCESS_KEY.is_empty(), "Access key should not be empty");
|
||||
assert!(DEFAULT_ACCESS_KEY.len() >= 8, "Access key should be at least 8 characters");
|
||||
|
||||
assert_eq!(DEFAULT_SECRET_KEY, "rustfsadmin");
|
||||
assert!(!DEFAULT_SECRET_KEY.is_empty(), "Secret key should not be empty");
|
||||
assert!(DEFAULT_SECRET_KEY.len() >= 8, "Secret key should be at least 8 characters");
|
||||
|
||||
// In production environment, access key and secret key should be different
|
||||
// These are default values, so being the same is acceptable, but should be warned in documentation
|
||||
println!("Warning: Default access key and secret key are the same. Change them in production!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_file_path_constants() {
|
||||
// Test file path related constants
|
||||
assert_eq!(DEFAULT_OBS_CONFIG, "./deploy/config/obs.toml");
|
||||
assert!(DEFAULT_OBS_CONFIG.ends_with(".toml"), "Config file should be TOML format");
|
||||
assert!(!DEFAULT_OBS_CONFIG.is_empty(), "Config path should not be empty");
|
||||
|
||||
assert_eq!(RUSTFS_TLS_KEY, "rustfs_key.pem");
|
||||
assert!(RUSTFS_TLS_KEY.ends_with(".pem"), "TLS key should be PEM format");
|
||||
|
||||
assert_eq!(RUSTFS_TLS_CERT, "rustfs_cert.pem");
|
||||
assert!(RUSTFS_TLS_CERT.ends_with(".pem"), "TLS cert should be PEM format");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_port_constants() {
|
||||
// Test port related constants
|
||||
assert_eq!(DEFAULT_PORT, 9000);
|
||||
assert!(DEFAULT_PORT > 1024, "Default port should be above reserved range");
|
||||
// u16 type automatically ensures port is in valid range (0-65535)
|
||||
|
||||
assert_eq!(DEFAULT_CONSOLE_PORT, 9002);
|
||||
assert!(DEFAULT_CONSOLE_PORT > 1024, "Console port should be above reserved range");
|
||||
// u16 type automatically ensures port is in valid range (0-65535)
|
||||
|
||||
assert_ne!(DEFAULT_PORT, DEFAULT_CONSOLE_PORT, "Main port and console port should be different");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_address_constants() {
|
||||
// Test address related constants
|
||||
assert_eq!(DEFAULT_ADDRESS, ":9000");
|
||||
assert!(DEFAULT_ADDRESS.starts_with(':'), "Address should start with colon");
|
||||
assert!(
|
||||
DEFAULT_ADDRESS.contains(&DEFAULT_PORT.to_string()),
|
||||
"Address should contain the default port"
|
||||
);
|
||||
|
||||
assert_eq!(DEFAULT_CONSOLE_ADDRESS, ":9002");
|
||||
assert!(DEFAULT_CONSOLE_ADDRESS.starts_with(':'), "Console address should start with colon");
|
||||
assert!(
|
||||
DEFAULT_CONSOLE_ADDRESS.contains(&DEFAULT_CONSOLE_PORT.to_string()),
|
||||
"Console address should contain the console port"
|
||||
);
|
||||
|
||||
assert_ne!(
|
||||
DEFAULT_ADDRESS, DEFAULT_CONSOLE_ADDRESS,
|
||||
"Main address and console address should be different"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_const_str_concat_functionality() {
|
||||
// Test const_str::concat macro functionality
|
||||
let expected_address = format!(":{}", DEFAULT_PORT);
|
||||
assert_eq!(DEFAULT_ADDRESS, expected_address);
|
||||
|
||||
let expected_console_address = format!(":{}", DEFAULT_CONSOLE_PORT);
|
||||
assert_eq!(DEFAULT_CONSOLE_ADDRESS, expected_console_address);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_constants_validity() {
|
||||
// Test validity of string constants
|
||||
let string_constants = [
|
||||
APP_NAME,
|
||||
VERSION,
|
||||
DEFAULT_LOG_LEVEL,
|
||||
SERVICE_VERSION,
|
||||
ENVIRONMENT,
|
||||
DEFAULT_ACCESS_KEY,
|
||||
DEFAULT_SECRET_KEY,
|
||||
DEFAULT_OBS_CONFIG,
|
||||
RUSTFS_TLS_KEY,
|
||||
RUSTFS_TLS_CERT,
|
||||
DEFAULT_ADDRESS,
|
||||
DEFAULT_CONSOLE_ADDRESS,
|
||||
];
|
||||
|
||||
for constant in &string_constants {
|
||||
assert!(!constant.is_empty(), "String constant should not be empty: {}", constant);
|
||||
assert!(!constant.starts_with(' '), "String constant should not start with space: {}", constant);
|
||||
assert!(!constant.ends_with(' '), "String constant should not end with space: {}", constant);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_numeric_constants_validity() {
|
||||
// Test validity of numeric constants
|
||||
assert!(SAMPLE_RATIO.is_finite(), "Sample ratio should be finite");
|
||||
assert!(!SAMPLE_RATIO.is_nan(), "Sample ratio should not be NaN");
|
||||
|
||||
assert!(METER_INTERVAL < u64::MAX, "Meter interval should be reasonable");
|
||||
assert!(MAX_CONNECTIONS < usize::MAX, "Max connections should be reasonable");
|
||||
assert!(DEFAULT_TIMEOUT_MS < u64::MAX, "Timeout should be reasonable");
|
||||
|
||||
assert!(DEFAULT_PORT != 0, "Default port should not be zero");
|
||||
assert!(DEFAULT_CONSOLE_PORT != 0, "Console port should not be zero");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_security_best_practices() {
|
||||
// Test security best practices
|
||||
|
||||
// These are default values, should be changed in production environments
|
||||
println!("Security Warning: Default credentials detected!");
|
||||
println!("Access Key: {}", DEFAULT_ACCESS_KEY);
|
||||
println!("Secret Key: {}", DEFAULT_SECRET_KEY);
|
||||
println!("These should be changed in production environments!");
|
||||
|
||||
// Verify that key lengths meet minimum security requirements
|
||||
assert!(DEFAULT_ACCESS_KEY.len() >= 8, "Access key should be at least 8 characters");
|
||||
assert!(DEFAULT_SECRET_KEY.len() >= 8, "Secret key should be at least 8 characters");
|
||||
|
||||
// Check if default credentials contain common insecure patterns
|
||||
let _insecure_patterns = ["admin", "password", "123456", "default"];
|
||||
let _access_key_lower = DEFAULT_ACCESS_KEY.to_lowercase();
|
||||
let _secret_key_lower = DEFAULT_SECRET_KEY.to_lowercase();
|
||||
|
||||
// Note: More security check logic can be added here
|
||||
// For example, check if keys contain insecure patterns
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_configuration_consistency() {
|
||||
// Test configuration consistency
|
||||
|
||||
// Version consistency
|
||||
assert_eq!(VERSION, SERVICE_VERSION, "Application version should match service version");
|
||||
|
||||
// Port conflict check
|
||||
let ports = [DEFAULT_PORT, DEFAULT_CONSOLE_PORT];
|
||||
let mut unique_ports = std::collections::HashSet::new();
|
||||
for port in &ports {
|
||||
assert!(unique_ports.insert(port), "Port {} is duplicated", port);
|
||||
}
|
||||
|
||||
// Address format consistency
|
||||
assert_eq!(DEFAULT_ADDRESS, format!(":{}", DEFAULT_PORT));
|
||||
assert_eq!(DEFAULT_CONSOLE_ADDRESS, format!(":{}", DEFAULT_CONSOLE_PORT));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,3 +46,375 @@ impl Error {
|
||||
Self::Custom(msg.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::error::Error as StdError;
|
||||
use std::io;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
#[test]
|
||||
fn test_error_display() {
|
||||
// Test error message display
|
||||
let custom_error = Error::custom("test message");
|
||||
assert_eq!(custom_error.to_string(), "Custom error: test message");
|
||||
|
||||
let feature_error = Error::FeatureDisabled("test feature");
|
||||
assert_eq!(feature_error.to_string(), "Feature disabled: test feature");
|
||||
|
||||
let event_bus_error = Error::EventBusStarted;
|
||||
assert_eq!(event_bus_error.to_string(), "Event bus already started");
|
||||
|
||||
let missing_field_error = Error::MissingField("required_field");
|
||||
assert_eq!(missing_field_error.to_string(), "necessary fields are missing:required_field");
|
||||
|
||||
let validation_error = Error::ValidationError("invalid format");
|
||||
assert_eq!(validation_error.to_string(), "field verification failed:invalid format");
|
||||
|
||||
let config_error = Error::ConfigError("invalid config".to_string());
|
||||
assert_eq!(config_error.to_string(), "Configuration error: invalid config");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_debug() {
|
||||
// Test Debug trait implementation
|
||||
let custom_error = Error::custom("debug test");
|
||||
let debug_str = format!("{:?}", custom_error);
|
||||
assert!(debug_str.contains("Custom"));
|
||||
assert!(debug_str.contains("debug test"));
|
||||
|
||||
let feature_error = Error::FeatureDisabled("debug feature");
|
||||
let debug_str = format!("{:?}", feature_error);
|
||||
assert!(debug_str.contains("FeatureDisabled"));
|
||||
assert!(debug_str.contains("debug feature"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_custom_error_creation() {
|
||||
// Test custom error creation
|
||||
let error = Error::custom("test custom error");
|
||||
match error {
|
||||
Error::Custom(msg) => assert_eq!(msg, "test custom error"),
|
||||
_ => panic!("Expected Custom error variant"),
|
||||
}
|
||||
|
||||
// Test empty string
|
||||
let empty_error = Error::custom("");
|
||||
match empty_error {
|
||||
Error::Custom(msg) => assert_eq!(msg, ""),
|
||||
_ => panic!("Expected Custom error variant"),
|
||||
}
|
||||
|
||||
// Test special characters
|
||||
let special_error = Error::custom("Test Chinese 中文 & special chars: !@#$%");
|
||||
match special_error {
|
||||
Error::Custom(msg) => assert_eq!(msg, "Test Chinese 中文 & special chars: !@#$%"),
|
||||
_ => panic!("Expected Custom error variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_io_error_conversion() {
|
||||
// Test IO error conversion
|
||||
let io_error = io::Error::new(io::ErrorKind::NotFound, "file not found");
|
||||
let converted_error: Error = io_error.into();
|
||||
|
||||
match converted_error {
|
||||
Error::Io(err) => {
|
||||
assert_eq!(err.kind(), io::ErrorKind::NotFound);
|
||||
assert_eq!(err.to_string(), "file not found");
|
||||
}
|
||||
_ => panic!("Expected Io error variant"),
|
||||
}
|
||||
|
||||
// Test different types of IO errors
|
||||
let permission_error = io::Error::new(io::ErrorKind::PermissionDenied, "access denied");
|
||||
let converted: Error = permission_error.into();
|
||||
assert!(matches!(converted, Error::Io(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serde_error_conversion() {
|
||||
// Test serialization error conversion
|
||||
let invalid_json = r#"{"invalid": json}"#;
|
||||
let serde_error = serde_json::from_str::<serde_json::Value>(invalid_json).unwrap_err();
|
||||
let converted_error: Error = serde_error.into();
|
||||
|
||||
match converted_error {
|
||||
Error::Serde(_) => {
|
||||
// Verify error type is correct
|
||||
assert!(converted_error.to_string().contains("Serialization error"));
|
||||
}
|
||||
_ => panic!("Expected Serde error variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_config_error_conversion() {
|
||||
// Test configuration error conversion
|
||||
let config_error = ConfigError::Message("invalid configuration".to_string());
|
||||
let converted_error: Error = config_error.into();
|
||||
|
||||
match converted_error {
|
||||
Error::Config(_) => {
|
||||
assert!(converted_error.to_string().contains("Configuration loading error"));
|
||||
}
|
||||
_ => panic!("Expected Config error variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_channel_send_error_conversion() {
|
||||
// Test channel send error conversion
|
||||
let (tx, rx) = mpsc::channel::<crate::event::Event>(1);
|
||||
drop(rx); // Close receiver
|
||||
|
||||
// Create a test event
|
||||
use crate::event::{Bucket, Identity, Metadata, Name, Object, Source};
|
||||
use std::collections::HashMap;
|
||||
|
||||
let identity = Identity::new("test-user".to_string());
|
||||
let bucket = Bucket::new("test-bucket".to_string(), identity.clone(), "arn:aws:s3:::test-bucket".to_string());
|
||||
let object = Object::new(
|
||||
"test-key".to_string(),
|
||||
Some(1024),
|
||||
Some("etag123".to_string()),
|
||||
Some("text/plain".to_string()),
|
||||
Some(HashMap::new()),
|
||||
None,
|
||||
"sequencer123".to_string(),
|
||||
);
|
||||
let metadata = Metadata::create("1.0".to_string(), "config1".to_string(), bucket, object);
|
||||
let source = Source::new("localhost".to_string(), "8080".to_string(), "test-agent".to_string());
|
||||
|
||||
let test_event = crate::event::Event::builder()
|
||||
.event_name(Name::ObjectCreatedPut)
|
||||
.s3(metadata)
|
||||
.source(source)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let send_result = tx.send(test_event).await;
|
||||
assert!(send_result.is_err());
|
||||
|
||||
let send_error = send_result.unwrap_err();
|
||||
let boxed_error = Box::new(send_error);
|
||||
let converted_error: Error = boxed_error.into();
|
||||
|
||||
match converted_error {
|
||||
Error::ChannelSend(_) => {
|
||||
assert!(converted_error.to_string().contains("Channel send error"));
|
||||
}
|
||||
_ => panic!("Expected ChannelSend error variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_source_chain() {
|
||||
// 测试错误源链
|
||||
let io_error = io::Error::new(io::ErrorKind::InvalidData, "invalid data");
|
||||
let converted_error: Error = io_error.into();
|
||||
|
||||
// 验证错误源
|
||||
assert!(converted_error.source().is_some());
|
||||
let source = converted_error.source().unwrap();
|
||||
assert_eq!(source.to_string(), "invalid data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_variants_exhaustive() {
|
||||
// 测试所有错误变体的创建
|
||||
let errors = vec![
|
||||
Error::FeatureDisabled("test"),
|
||||
Error::EventBusStarted,
|
||||
Error::MissingField("field"),
|
||||
Error::ValidationError("validation"),
|
||||
Error::Custom("custom".to_string()),
|
||||
Error::ConfigError("config".to_string()),
|
||||
];
|
||||
|
||||
for error in errors {
|
||||
// 验证每个错误都能正确显示
|
||||
let error_str = error.to_string();
|
||||
assert!(!error_str.is_empty());
|
||||
|
||||
// 验证每个错误都能正确调试
|
||||
let debug_str = format!("{:?}", error);
|
||||
assert!(!debug_str.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_equality_and_matching() {
|
||||
// 测试错误的模式匹配
|
||||
let custom_error = Error::custom("test");
|
||||
match custom_error {
|
||||
Error::Custom(msg) => assert_eq!(msg, "test"),
|
||||
_ => panic!("Pattern matching failed"),
|
||||
}
|
||||
|
||||
let feature_error = Error::FeatureDisabled("feature");
|
||||
match feature_error {
|
||||
Error::FeatureDisabled(feature) => assert_eq!(feature, "feature"),
|
||||
_ => panic!("Pattern matching failed"),
|
||||
}
|
||||
|
||||
let event_bus_error = Error::EventBusStarted;
|
||||
match event_bus_error {
|
||||
Error::EventBusStarted => {} // 正确匹配
|
||||
_ => panic!("Pattern matching failed"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_message_formatting() {
|
||||
// 测试错误消息格式化
|
||||
let test_cases = vec![
|
||||
(Error::FeatureDisabled("kafka"), "Feature disabled: kafka"),
|
||||
(Error::MissingField("bucket_name"), "necessary fields are missing:bucket_name"),
|
||||
(Error::ValidationError("invalid email"), "field verification failed:invalid email"),
|
||||
(Error::ConfigError("missing file".to_string()), "Configuration error: missing file"),
|
||||
];
|
||||
|
||||
for (error, expected_message) in test_cases {
|
||||
assert_eq!(error.to_string(), expected_message);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_memory_efficiency() {
|
||||
// 测试错误类型的内存效率
|
||||
use std::mem;
|
||||
|
||||
let size = mem::size_of::<Error>();
|
||||
// 错误类型应该相对紧凑,考虑到包含多种错误类型,96字节是合理的
|
||||
assert!(size <= 128, "Error size should be reasonable, got {} bytes", size);
|
||||
|
||||
// 测试Option<Error>的大小
|
||||
let option_size = mem::size_of::<Option<Error>>();
|
||||
assert!(option_size <= 136, "Option<Error> should be efficient, got {} bytes", option_size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_thread_safety() {
|
||||
// 测试错误类型的线程安全性
|
||||
fn assert_send<T: Send>() {}
|
||||
fn assert_sync<T: Sync>() {}
|
||||
|
||||
assert_send::<Error>();
|
||||
assert_sync::<Error>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_custom_error_edge_cases() {
|
||||
// 测试自定义错误的边界情况
|
||||
let long_message = "a".repeat(1000);
|
||||
let long_error = Error::custom(&long_message);
|
||||
match long_error {
|
||||
Error::Custom(msg) => assert_eq!(msg.len(), 1000),
|
||||
_ => panic!("Expected Custom error variant"),
|
||||
}
|
||||
|
||||
// 测试包含换行符的消息
|
||||
let multiline_error = Error::custom("line1\nline2\nline3");
|
||||
match multiline_error {
|
||||
Error::Custom(msg) => assert!(msg.contains('\n')),
|
||||
_ => panic!("Expected Custom error variant"),
|
||||
}
|
||||
|
||||
// 测试包含Unicode字符的消息
|
||||
let unicode_error = Error::custom("🚀 Unicode test 测试 🎉");
|
||||
match unicode_error {
|
||||
Error::Custom(msg) => assert!(msg.contains('🚀')),
|
||||
_ => panic!("Expected Custom error variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_conversion_consistency() {
|
||||
// 测试错误转换的一致性
|
||||
let original_io_error = io::Error::new(io::ErrorKind::TimedOut, "timeout");
|
||||
let error_message = original_io_error.to_string();
|
||||
let converted: Error = original_io_error.into();
|
||||
|
||||
// 验证转换后的错误包含原始错误信息
|
||||
assert!(converted.to_string().contains(&error_message));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_downcast() {
|
||||
// 测试错误的向下转型
|
||||
let io_error = io::Error::new(io::ErrorKind::Other, "test error");
|
||||
let converted: Error = io_error.into();
|
||||
|
||||
// 验证可以获取源错误
|
||||
if let Error::Io(ref inner) = converted {
|
||||
assert_eq!(inner.to_string(), "test error");
|
||||
assert_eq!(inner.kind(), io::ErrorKind::Other);
|
||||
} else {
|
||||
panic!("Expected Io error variant");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_chain_depth() {
|
||||
// 测试错误链的深度
|
||||
let root_cause = io::Error::new(io::ErrorKind::Other, "root cause");
|
||||
let converted: Error = root_cause.into();
|
||||
|
||||
let mut depth = 0;
|
||||
let mut current_error: &dyn StdError = &converted;
|
||||
|
||||
while let Some(source) = current_error.source() {
|
||||
depth += 1;
|
||||
current_error = source;
|
||||
// 防止无限循环
|
||||
if depth > 10 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assert!(depth > 0, "Error should have at least one source");
|
||||
assert!(depth <= 3, "Error chain should not be too deep");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_static_str_lifetime() {
|
||||
// 测试静态字符串生命周期
|
||||
fn create_feature_error() -> Error {
|
||||
Error::FeatureDisabled("static_feature")
|
||||
}
|
||||
|
||||
let error = create_feature_error();
|
||||
match error {
|
||||
Error::FeatureDisabled(feature) => assert_eq!(feature, "static_feature"),
|
||||
_ => panic!("Expected FeatureDisabled error variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_formatting_consistency() {
|
||||
// 测试错误格式化的一致性
|
||||
let errors = vec![
|
||||
Error::FeatureDisabled("test"),
|
||||
Error::MissingField("field"),
|
||||
Error::ValidationError("validation"),
|
||||
Error::Custom("custom".to_string()),
|
||||
];
|
||||
|
||||
for error in errors {
|
||||
let display_str = error.to_string();
|
||||
let debug_str = format!("{:?}", error);
|
||||
|
||||
// Display和Debug都不应该为空
|
||||
assert!(!display_str.is_empty());
|
||||
assert!(!debug_str.is_empty());
|
||||
|
||||
// Debug输出通常包含更多信息,但不是绝对的
|
||||
// 这里我们只验证两者都有内容即可
|
||||
assert!(debug_str.len() > 0);
|
||||
assert!(display_str.len() > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,4 +22,5 @@ default = ["ip"] # features that are enabled by default
|
||||
ip = ["dep:local-ip-address"] # ip characteristics and their dependencies
|
||||
tls = ["dep:rustls", "dep:rustls-pemfile", "dep:rustls-pki-types"] # tls characteristics and their dependencies
|
||||
net = ["ip"] # empty network features
|
||||
full = ["ip", "tls", "net"] # all features
|
||||
integration = [] # integration test features
|
||||
full = ["ip", "tls", "net", "integration"] # all features
|
||||
|
||||
+165
-5
@@ -31,13 +31,173 @@ pub fn get_local_ip_with_default() -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
#[test]
|
||||
fn test_get_local_ip() {
|
||||
match get_local_ip() {
|
||||
Some(ip) => println!("the ip address of this machine:{}", ip),
|
||||
None => println!("Unable to obtain the IP address of the machine"),
|
||||
fn test_get_local_ip_returns_some_ip() {
|
||||
// Test getting local IP address, should return Some value
|
||||
let ip = get_local_ip();
|
||||
assert!(ip.is_some(), "Should be able to get local IP address");
|
||||
|
||||
if let Some(ip_addr) = ip {
|
||||
println!("Local IP address: {}", ip_addr);
|
||||
// Verify that the returned IP address is valid
|
||||
match ip_addr {
|
||||
IpAddr::V4(ipv4) => {
|
||||
assert!(!ipv4.is_unspecified(), "IPv4 should not be unspecified (0.0.0.0)");
|
||||
println!("Got IPv4 address: {}", ipv4);
|
||||
}
|
||||
IpAddr::V6(ipv6) => {
|
||||
assert!(!ipv6.is_unspecified(), "IPv6 should not be unspecified (::)");
|
||||
println!("Got IPv6 address: {}", ipv6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_local_ip_with_default_never_empty() {
|
||||
// Test that function with default value never returns empty string
|
||||
let ip_string = get_local_ip_with_default();
|
||||
assert!(!ip_string.is_empty(), "IP string should never be empty");
|
||||
|
||||
// Verify that the returned string can be parsed as a valid IP address
|
||||
let parsed_ip: Result<IpAddr, _> = ip_string.parse();
|
||||
assert!(parsed_ip.is_ok(), "Returned string should be a valid IP address: {}", ip_string);
|
||||
|
||||
println!("Local IP with default: {}", ip_string);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_local_ip_with_default_fallback() {
|
||||
// Test whether the default value is 127.0.0.1
|
||||
let default_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
|
||||
let ip_string = get_local_ip_with_default();
|
||||
|
||||
// If unable to get real IP, should return default value
|
||||
if get_local_ip().is_none() {
|
||||
assert_eq!(ip_string, default_ip.to_string());
|
||||
}
|
||||
|
||||
// In any case, should always return a valid IP address string
|
||||
let parsed: Result<IpAddr, _> = ip_string.parse();
|
||||
assert!(parsed.is_ok(), "Should always return a valid IP string");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ip_address_types() {
|
||||
// Test IP address type recognition
|
||||
if let Some(ip) = get_local_ip() {
|
||||
match ip {
|
||||
IpAddr::V4(ipv4) => {
|
||||
// Test IPv4 address properties
|
||||
println!("IPv4 address: {}", ipv4);
|
||||
assert!(!ipv4.is_multicast(), "Local IP should not be multicast");
|
||||
assert!(!ipv4.is_broadcast(), "Local IP should not be broadcast");
|
||||
|
||||
// Check if it's a private address (usually local IP is private)
|
||||
let is_private = ipv4.is_private();
|
||||
let is_loopback = ipv4.is_loopback();
|
||||
println!("IPv4 is private: {}, is loopback: {}", is_private, is_loopback);
|
||||
}
|
||||
IpAddr::V6(ipv6) => {
|
||||
// Test IPv6 address properties
|
||||
println!("IPv6 address: {}", ipv6);
|
||||
assert!(!ipv6.is_multicast(), "Local IP should not be multicast");
|
||||
|
||||
let is_loopback = ipv6.is_loopback();
|
||||
println!("IPv6 is loopback: {}", is_loopback);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ip_string_format() {
|
||||
// Test IP address string format
|
||||
let ip_string = get_local_ip_with_default();
|
||||
|
||||
// Verify string format
|
||||
assert!(!ip_string.contains(' '), "IP string should not contain spaces");
|
||||
assert!(!ip_string.is_empty(), "IP string should not be empty");
|
||||
|
||||
// Verify round-trip conversion
|
||||
let parsed_ip: IpAddr = ip_string.parse().expect("Should parse as valid IP");
|
||||
let back_to_string = parsed_ip.to_string();
|
||||
|
||||
// For standard IP addresses, round-trip conversion should be consistent
|
||||
println!("Original: {}, Parsed back: {}", ip_string, back_to_string);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_fallback_value() {
|
||||
// Test correctness of default fallback value
|
||||
let default_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
|
||||
assert_eq!(default_ip.to_string(), "127.0.0.1");
|
||||
|
||||
// Verify default IP properties
|
||||
if let IpAddr::V4(ipv4) = default_ip {
|
||||
assert!(ipv4.is_loopback(), "Default IP should be loopback");
|
||||
assert!(!ipv4.is_unspecified(), "Default IP should not be unspecified");
|
||||
assert!(!ipv4.is_multicast(), "Default IP should not be multicast");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_consistency_between_functions() {
|
||||
// Test consistency between the two functions
|
||||
let ip_option = get_local_ip();
|
||||
let ip_string = get_local_ip_with_default();
|
||||
|
||||
match ip_option {
|
||||
Some(ip) => {
|
||||
// If get_local_ip returns Some, then get_local_ip_with_default should return the same IP
|
||||
assert_eq!(ip.to_string(), ip_string, "Both functions should return the same IP when available");
|
||||
}
|
||||
None => {
|
||||
// If get_local_ip returns None, then get_local_ip_with_default should return default value
|
||||
assert_eq!(ip_string, "127.0.0.1", "Should return default value when no IP is available");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiple_calls_consistency() {
|
||||
// Test consistency of multiple calls
|
||||
let ip1 = get_local_ip();
|
||||
let ip2 = get_local_ip();
|
||||
let ip_str1 = get_local_ip_with_default();
|
||||
let ip_str2 = get_local_ip_with_default();
|
||||
|
||||
// Multiple calls should return the same result
|
||||
assert_eq!(ip1, ip2, "Multiple calls to get_local_ip should return same result");
|
||||
assert_eq!(ip_str1, ip_str2, "Multiple calls to get_local_ip_with_default should return same result");
|
||||
}
|
||||
|
||||
#[cfg(feature = "integration")]
|
||||
#[test]
|
||||
fn test_network_connectivity() {
|
||||
// Integration test: verify that the obtained IP address can be used for network connections
|
||||
if let Some(ip) = get_local_ip() {
|
||||
match ip {
|
||||
IpAddr::V4(ipv4) => {
|
||||
// For IPv4, check if it's a valid network address
|
||||
assert!(!ipv4.is_unspecified(), "Should not be 0.0.0.0");
|
||||
|
||||
// If it's not a loopback address, it should be routable
|
||||
if !ipv4.is_loopback() {
|
||||
println!("Got routable IPv4: {}", ipv4);
|
||||
}
|
||||
}
|
||||
IpAddr::V6(ipv6) => {
|
||||
// For IPv6, check if it's a valid network address
|
||||
assert!(!ipv6.is_unspecified(), "Should not be ::");
|
||||
|
||||
if !ipv6.is_loopback() {
|
||||
println!("Got routable IPv6: {}", ipv6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(get_local_ip().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "zip"
|
||||
name = "rustfs-zip"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
@@ -16,8 +16,8 @@ async-compression = { version = "0.4.0", features = [
|
||||
"zstd",
|
||||
"xz",
|
||||
] }
|
||||
# async_zip = { version = "0.0.17", features = ["tokio"] }
|
||||
# rc-zip-tokio = "4.2.6"
|
||||
async_zip = { version = "0.0.17", features = ["tokio"] }
|
||||
zip = "2.2.0"
|
||||
tokio = { version = "1.45.0", features = ["full"] }
|
||||
tokio-stream = "0.1.17"
|
||||
tokio-tar = { workspace = true }
|
||||
|
||||
+918
-44
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user