srb_std/error.rs
1/// Return with an error if a condition is not met.
2///
3/// Simplifies the pattern of checking for a condition and returning with an error.
4#[macro_export]
5macro_rules! ensure {
6 ($cond:expr, $e:expr $(,)?) => {
7 if !$cond {
8 return Err($e);
9 }
10 };
11}
12
13// The following definitions are mostly intended to serve as pseudo-documentation within tests
14// and help with convenience/clarity.
15
16/// Assert that a [`Result`] is [`Ok`]
17///
18/// If the provided expresion evaulates to [`Ok`], then the
19/// macro returns the value contained within the [`Ok`]. If
20/// the [`Result`] is an [`Err`] then the macro will [`panic`]
21/// with a message that includes the expression and the error.
22///
23/// This function was vendored from: https://docs.rs/assert_ok/1.0.2/assert_ok/
24#[macro_export]
25macro_rules! assert_ok {
26 ( $x:expr ) => {
27 match $x {
28 Ok(v) => v,
29 Err(e) => {
30 panic!("Error calling {}: {:?}", stringify!($x), e);
31 }
32 }
33 };
34}
35
36/// Assert that a [`Result`] is [`Err`] and matches an error variant
37#[macro_export]
38macro_rules! assert_err {
39 ( $x:expr, $expected:pat ) => {
40 match $x {
41 Err(e) => {
42 if !matches!(e, $expected) {
43 panic!("Expected error {}: {:?}", stringify!($expected), e);
44 }
45 }
46 Ok(v) => {
47 panic!("Expected error {}, found {:?}", stringify!($expected), v)
48 }
49 }
50 };
51}
52
53/// Assert that a [`Result`] from a contract call is [`Err`] and matches an error variant
54///
55/// `given` corresponds to the return type from `try_*` functions in Soroban.
56/// For the assert to succeed, the function needs to fail and successfully pass
57/// down the intended error type. So, the parameters would be in the form:
58///
59/// given: `Err(Ok(ContractError))`
60/// expected: `ContractError`
61///
62/// Putting it together in a function call:
63///
64/// `assert_contract_err(client.try_fun(...), ContractError);`
65#[macro_export]
66macro_rules! assert_contract_err {
67 ($given:expr, $expected:pat) => {
68 match $given {
69 Ok(v) => panic!(
70 "Expected error {:?}, got {:?} instead",
71 stringify!($expected),
72 v
73 ),
74 Err(e) => match e {
75 Ok(v) => {
76 if !matches!(v, $expected) {
77 panic!(
78 "Expected error {}, got {:?} instead",
79 stringify!($expected),
80 v
81 )
82 }
83 }
84 Err(e) => panic!("Unexpected error {e:?}"),
85 },
86 }
87 };
88}
89
90/// Assert that an [`Option`] is [`Some`]
91///
92/// If the provided expresion evaulates to [`Some`], then the
93/// macro returns the value contained within the [`Some`]. If
94/// the [`Option`] is [`None`] then the macro will [`panic`]
95/// with a message that includes the expression
96#[macro_export]
97macro_rules! assert_some {
98 ( $x:expr ) => {
99 match $x {
100 core::option::Option::Some(s) => s,
101 core::option::Option::None => {
102 panic!("Expected value when calling {}, got None", stringify!($x));
103 }
104 }
105 };
106}