Skip to content

Commit

Permalink
Add try_fail_point!
Browse files Browse the repository at this point in the history
In my project I have a ton of code which uses `anyhow::Result`.  I
want a convenient way to force a function to return a stock error
from a failpoint.  Today this requires something like:

```
    fail::fail_point!("main", true, |msg| {
        let msg = msg.as_deref().unwrap_or("synthetic error");
        Err(anyhow::anyhow!("{msg}"))
    });
```
which is cumbersome to copy around.

Now, I conservatively made this a new macro.  I am not sure how
often the use case of a fail point for an infallible (i.e. non-`Result`)
function occurs.  It may make sense to require those to take
a distinct `inject_point!` or something?

Signed-off-by: Colin Walters <[email protected]>
  • Loading branch information
cgwalters committed Jan 6, 2023
1 parent 5bc95a1 commit d7cc281
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ log = { version = "0.4", features = ["std"] }
once_cell = "1.9.0"
rand = "0.8"

[dev-dependencies]
anyhow = "1.0"

[features]
failpoints = []

Expand Down
80 changes: 79 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,8 @@

use std::collections::HashMap;
use std::env::VarError;
use std::fmt::Debug;
use std::error::Error;
use std::fmt::{Debug, Display};
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, TryLockError};
Expand Down Expand Up @@ -428,6 +429,33 @@ impl FromStr for Action {
}
}

/// A synthetic error created as part of [`try_fail_point!`].
#[doc(hidden)]
#[derive(Debug)]
pub struct ReturnError(pub String);

impl ReturnError {
const SYNTHETIC: &str = "synthetic failpoint error";
}

impl From<Option<String>> for ReturnError {
fn from(msg: Option<String>) -> Self {
Self(msg.unwrap_or_else(|| Self::SYNTHETIC.to_string()))
}
}

impl Display for ReturnError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}

impl Error for ReturnError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}

#[cfg_attr(feature = "cargo-clippy", allow(clippy::mutex_atomic))]
#[derive(Debug)]
struct FailPoint {
Expand Down Expand Up @@ -843,6 +871,32 @@ macro_rules! fail_point {
}};
}

/// A variant of [`fail_point`] designed for a function that returns [`std::result::Result`].
///
/// ```rust
/// # #[macro_use] extern crate fail;
/// fn fallible_function() -> Result<u32, Box<dyn std::error::Error>> {
/// try_fail_point!("a-fail-point");
/// Ok(42)
/// }
/// ```
///
/// This
#[macro_export]
#[cfg(feature = "failpoints")]
macro_rules! try_fail_point {
($name:expr) => {{
if let Some(e) = $crate::eval($name, |msg| $crate::ReturnError::from(msg)) {
return Err(From::from(e));
}
}};
($name:expr, $cond:expr) => {{
if $cond {
$crate::try_fail_point!($name);
}
}};
}

/// Define a fail point (disabled, see `failpoints` feature).
#[macro_export]
#[cfg(not(feature = "failpoints"))]
Expand All @@ -852,6 +906,14 @@ macro_rules! fail_point {
($name:expr, $cond:expr, $e:expr) => {{}};
}

/// Define a fail point for a Result-returning function (disabled, see `failpoints` feature).
#[macro_export]
#[cfg(not(feature = "failpoints"))]
macro_rules! try_fail_point {
($name:expr) => {{}};
($name:expr, $cond:expr) => {{}};
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -1032,6 +1094,22 @@ mod tests {
}
}

#[test]
#[cfg(feature = "failpoints")]
fn test_try_failpoint() -> anyhow::Result<()> {
fn test_anyhow() -> anyhow::Result<()> {
try_fail_point!("tryfail-with-result");
Ok(())
}
fn test_stderr() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
try_fail_point!("tryfail-with-result-2");
Ok(())
}
test_anyhow()?;
test_stderr().map_err(anyhow::Error::msg)?;
Ok(())
}

// This case should be tested as integration case, but when calling `teardown` other cases
// like `test_pause` maybe also affected, so it's better keep it here.
#[test]
Expand Down

0 comments on commit d7cc281

Please sign in to comment.