use super::*;
use crate::test_utils::init_test_environment;
use crate::userdb::UserStore;
use serial_test::serial;
#[test]
fn test_from_serde_json_error() {
let json_error = serde_json::from_str::<serde_json::Value>("invalid json").unwrap_err();
let user_error = UserError::from(json_error);
match user_error {
UserError::InvalidData(msg) => {
assert!(
msg.contains("expected value"),
"Error message should contain the original error"
);
}
_ => panic!("Expected InvalidData variant"),
}
}
#[test]
fn test_from_redis_error() {
let redis_error = redis::RedisError::from((redis::ErrorKind::Io, "Connection refused"));
let user_error = UserError::from(redis_error);
match user_error {
UserError::Storage(msg) => {
assert!(
msg.contains("Connection refused"),
"Error message should contain the original error"
);
}
_ => panic!("Expected Storage variant"),
}
}
#[test]
fn test_error_propagation() {
fn validate_user_data(id: &str) -> Result<(), UserError> {
if id.is_empty() {
return Err(UserError::InvalidData(
"User ID cannot be empty".to_string(),
));
}
Ok(())
}
let result = validate_user_data("user123");
assert!(result.is_ok());
let result = validate_user_data("");
match result {
Err(UserError::InvalidData(msg)) => {
assert!(msg.contains("cannot be empty"));
}
_ => panic!("Expected InvalidData error"),
}
fn process_user(id: &str) -> Result<String, UserError> {
validate_user_data(id)?;
Ok(format!("Processed user {id}"))
}
let result = process_user("");
assert!(matches!(result, Err(UserError::InvalidData(_))));
}
#[tokio::test]
#[serial]
async fn test_not_found_error_in_context() {
init_test_environment().await;
let result = UserStore::get_user(
crate::session::UserId::new("nonexistent_user_id".to_string()).expect("Valid user ID"),
)
.await;
assert!(result.is_ok());
assert!(
result
.expect("Getting non-existent user should succeed")
.is_none()
);
async fn get_existing_user(id: &str) -> Result<crate::userdb::User, UserError> {
match UserStore::get_user(
crate::session::UserId::new(id.to_string()).expect("Valid user ID"),
)
.await?
{
Some(user) => Ok(user),
None => Err(UserError::NotFound),
}
}
let result = get_existing_user("nonexistent_user_id").await;
assert!(matches!(result, Err(UserError::NotFound)));
}
#[tokio::test]
#[serial]
async fn test_database_error_handling() {
init_test_environment().await;
async fn simulate_db_error() -> Result<(), UserError> {
Err(UserError::Storage("Simulated database error".to_string()))
}
async fn user_operation() -> Result<(), UserError> {
simulate_db_error().await?;
Ok(())
}
let result = user_operation().await;
match result {
Err(UserError::Storage(msg)) => {
assert!(msg.contains("Simulated database error"));
}
_ => panic!("Expected Storage error"),
}
}