expect_error_matching

Macro expect_error_matching 

Source
macro_rules! expect_error_matching {
    ($result:expr, $expected:pat => $cond:expr) => { ... };
    ($result:expr, $expected:pat) => { ... };
}
Expand description

Helper macro to match against an error stream, expecting a specific error. For use in tests. Panics if a matching error is not found. Multiple matches are allowed.

Parameters:

  • $result must be a Result<_, ErrorStream<E>>.
  • $expected is a pattern to match against the error.
  • $cond is an optional expression that should evaluate to true if the error matches. Variables from $expected are bound in $cond behind references. Do not use any asserts in $cond as it may be called against multiple errors.
use spacetimedb_data_structures::error_stream::{
    ErrorStream,
    CollectAllErrors,
    expect_error_matching
};

#[derive(PartialEq, Eq, Clone, Copy, Debug)]
struct CaseRef(u32);

#[derive(Debug)]
enum MyError {
    InsufficientSwag { amount: u32 },
    TooMuchSwag { reason: String, precedent: CaseRef },
    SomethingElse(String)
}

let result: Result<(), ErrorStream<MyError>> = vec![
    Err(MyError::TooMuchSwag {
        reason: "sunglasses indoors".into(),
        precedent: CaseRef(37)
    }.into()),
    Err(MyError::TooMuchSwag {
        reason: "fur coat".into(),
        precedent: CaseRef(55)
    }.into()),
    Err(MyError::SomethingElse(
        "non-service animals forbidden".into()
    ).into())
].into_iter().collect_all_errors();

// This will panic if the error stream does not contain
// an error matching `MyError::SomethingElse`.
expect_error_matching!(
    result,
    MyError::SomethingElse(_)
);

// This will panic if the error stream does not contain
// an error matching `MyError::TooMuchSwag`, plus some
// extra conditions.
expect_error_matching!(
    result,
    MyError::TooMuchSwag { reason, precedent } =>
        precedent == &CaseRef(37) && reason.contains("sunglasses")
);