Skip to content

Commit

Permalink
Merge pull request #474 from CosmWasm/allow-conversions-in-ensure
Browse files Browse the repository at this point in the history
Allow error type conversions in ensure! and ensure_eq!
  • Loading branch information
webmaster128 authored Oct 7, 2021
2 parents b616293 + 7907133 commit 1f0295e
Showing 1 changed file with 37 additions and 4 deletions.
41 changes: 37 additions & 4 deletions packages/cw0/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
macro_rules! ensure {
($cond:expr, $e:expr) => {
if !($cond) {
return Err($e);
return Err(std::convert::From::from($e));
}
};
}
Expand Down Expand Up @@ -43,9 +43,7 @@ macro_rules! fail_if {
#[macro_export]
macro_rules! ensure_eq {
($a:expr, $b:expr, $e:expr) => {
if $a != $b {
return Err($e);
}
ensure!($a == $b, $e);
};
}

Expand All @@ -55,6 +53,19 @@ mod test {

#[test]
fn ensure_works() {
fn check(a: usize, b: usize) -> Result<(), StdError> {
ensure!(a == b, StdError::generic_err("foobar"));
Ok(())
}

let err = check(5, 6).unwrap_err();
assert!(matches!(err, StdError::GenericErr { .. }));

check(5, 5).unwrap();
}

#[test]
fn ensure_can_infer_error_type() {
let check = |a, b| {
ensure!(a == b, StdError::generic_err("foobar"));
Ok(())
Expand All @@ -66,6 +77,28 @@ mod test {
check(5, 5).unwrap();
}

#[test]
fn ensure_can_convert_into() {
#[derive(Debug)]
struct ContractError;

impl From<StdError> for ContractError {
fn from(_original: StdError) -> Self {
ContractError
}
}

fn check(a: usize, b: usize) -> Result<(), ContractError> {
ensure!(a == b, StdError::generic_err("foobar"));
Ok(())
}

let err = check(5, 6).unwrap_err();
assert!(matches!(err, ContractError));

check(5, 5).unwrap();
}

#[test]
fn fail_if_works() {
let check = |a, b| {
Expand Down

0 comments on commit 1f0295e

Please sign in to comment.