use thiserror::Error;
#[derive(Error, Debug, Clone, PartialEq)]
pub enum IndicatorError {
#[error("Invalid parameter: {0}")]
InvalidParameter(String),
#[error("Insufficient data: {0}")]
InsufficientData(String),
#[error("Calculation error: {0}")]
CalculationError(String),
}
#[cfg(test)]
mod tests {
use super::*;
use std::fmt::{Debug, Display};
#[test]
fn test_invalid_parameter_error() {
let error = IndicatorError::InvalidParameter("Period must be greater than 0".to_string());
assert!(format!("{:?}", error).contains("InvalidParameter"));
assert!(format!("{:?}", error).contains("Period must be greater than 0"));
assert_eq!(
format!("{}", error),
"Invalid parameter: Period must be greater than 0"
);
}
#[test]
fn test_insufficient_data_error() {
let error = IndicatorError::InsufficientData("Need at least 14 data points".to_string());
assert!(format!("{:?}", error).contains("InsufficientData"));
assert!(format!("{:?}", error).contains("Need at least 14 data points"));
assert_eq!(
format!("{}", error),
"Insufficient data: Need at least 14 data points"
);
}
#[test]
fn test_calculation_error() {
let error = IndicatorError::CalculationError("Division by zero".to_string());
assert!(format!("{:?}", error).contains("CalculationError"));
assert!(format!("{:?}", error).contains("Division by zero"));
assert_eq!(format!("{}", error), "Calculation error: Division by zero");
}
#[test]
fn test_error_conversion() {
fn returns_indicator_error() -> Result<(), IndicatorError> {
Err(IndicatorError::InvalidParameter("Test error".to_string()))
}
fn propagates_error() -> Result<(), IndicatorError> {
returns_indicator_error()?;
Ok(())
}
let result = propagates_error();
assert!(result.is_err());
if let Err(error) = result {
match error {
IndicatorError::InvalidParameter(msg) => {
assert_eq!(msg, "Test error");
}
_ => panic!("Wrong error type"),
}
}
}
fn assert_traits<T: Debug + Display + std::error::Error>() {}
#[test]
fn test_error_traits() {
assert_traits::<IndicatorError>();
}
}