use crate::StorageError;
pub fn finish_with_flush<T, E>(
command: Result<T, E>,
flush: Result<(), StorageError>,
) -> Result<T, E>
where
E: From<StorageError>,
{
flush?;
command
}
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
use super::*;
#[derive(Debug)]
enum StandInError {
Command,
Storage(StorageError),
}
impl From<StorageError> for StandInError {
fn from(error: StorageError) -> Self {
Self::Storage(error)
}
}
fn flush_failure() -> StorageError {
StorageError::NotFound {
key: "cache-epoch".to_owned(),
}
}
#[test]
fn returns_the_value_when_both_succeed() {
let value =
finish_with_flush::<_, StandInError>(Ok("done"), Ok(())).expect("both succeeded");
assert_eq!(value, "done");
}
#[test]
fn surfaces_a_flush_failure_after_a_successful_command() {
let error = finish_with_flush::<&str, StandInError>(Ok("done"), Err(flush_failure()))
.expect_err("the flush failed");
assert!(
matches!(error, StandInError::Storage(StorageError::NotFound { .. })),
"expected the flush error, got {error:?}"
);
}
#[test]
fn returns_the_command_error_when_the_flush_succeeds() {
let error = finish_with_flush::<&str, StandInError>(Err(StandInError::Command), Ok(()))
.expect_err("the command failed");
assert!(
matches!(error, StandInError::Command),
"expected the command error, got {error:?}"
);
}
#[test]
fn prefers_the_flush_failure_over_a_failed_command() {
let error = finish_with_flush::<&str, StandInError>(
Err(StandInError::Command),
Err(flush_failure()),
)
.expect_err("both failed");
assert!(
matches!(error, StandInError::Storage(StorageError::NotFound { .. })),
"expected the flush error to win, got {error:?}"
);
}
}