Skip to content

Commit

Permalink
Add defensive_assert! macro (paritytech#13423)
Browse files Browse the repository at this point in the history
* Add defensive_assert macro

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Apply review suggestions

Co-authored-by: Bastian Köcher <git@kchr.de>

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

---------

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
  • Loading branch information
ggwpez authored and ark0f committed Feb 27, 2023
1 parent 180806c commit 3adda45
Showing 1 changed file with 42 additions and 2 deletions.
44 changes: 42 additions & 2 deletions frame/support/src/traits/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ macro_rules! defensive {
);
debug_assert!(false, "{}", $crate::traits::DEFENSIVE_OP_INTERNAL_ERROR);
};
($error:tt) => {
($error:expr $(,)?) => {
frame_support::log::error!(
target: "runtime",
"{}: {:?}",
Expand All @@ -58,7 +58,7 @@ macro_rules! defensive {
);
debug_assert!(false, "{}: {:?}", $crate::traits::DEFENSIVE_OP_INTERNAL_ERROR, $error);
};
($error:tt, $proof:tt) => {
($error:expr, $proof:expr $(,)?) => {
frame_support::log::error!(
target: "runtime",
"{}: {:?}: {:?}",
Expand All @@ -70,6 +70,25 @@ macro_rules! defensive {
}
}

/// Trigger a defensive failure if a condition is not met.
///
/// Similar to [`assert!`] but will print an error without `debug_assertions` instead of silently
/// ignoring it. Only accepts one instead of variable formatting arguments.
///
/// # Example
///
/// ```should_panic
/// frame_support::defensive_assert!(1 == 0, "Must fail")
/// ```
#[macro_export]
macro_rules! defensive_assert {
($cond:expr $(, $proof:expr )? $(,)?) => {
if !($cond) {
$crate::defensive!(::core::stringify!($cond) $(, $proof )?);
}
};
}

/// Prelude module for all defensive traits to be imported at once.
pub mod defensive_prelude {
pub use super::{Defensive, DefensiveOption, DefensiveResult};
Expand Down Expand Up @@ -1141,6 +1160,27 @@ mod test {
use sp_core::bounded::{BoundedSlice, BoundedVec};
use sp_std::marker::PhantomData;

#[test]
fn defensive_assert_works() {
defensive_assert!(true);
defensive_assert!(true,);
defensive_assert!(true, "must work");
defensive_assert!(true, "must work",);
}

#[test]
#[cfg(debug_assertions)]
#[should_panic(expected = "Defensive failure has been triggered!: \"1 == 0\": \"Must fail\"")]
fn defensive_assert_panics() {
defensive_assert!(1 == 0, "Must fail");
}

#[test]
#[cfg(not(debug_assertions))]
fn defensive_assert_does_not_panic() {
defensive_assert!(1 == 0, "Must fail");
}

#[test]
#[cfg(not(debug_assertions))]
fn defensive_saturating_accrue_works() {
Expand Down

0 comments on commit 3adda45

Please sign in to comment.