Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Commit

Permalink
chore: add arbitrary order macro for more resilient subsystem tests
Browse files Browse the repository at this point in the history
  • Loading branch information
drahnr committed Sep 1, 2021
1 parent fd486f2 commit 8477d14
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
30 changes: 30 additions & 0 deletions node/subsystem-util/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -752,3 +752,33 @@ where
SpawnedSubsystem { name: Job::NAME.strip_suffix("Job").unwrap_or(Job::NAME), future }
}
}

/// Asserts that two patterns match, yet only one
#[macro_export]
macro_rules! arbitrary_order {
($rx:expr; $p1:pat => $e1:expr; $p2:pat => $e2:expr) => {
// If i.e. a enum has only two variants, `_` is unreachable.
match $rx {
$p1 => {
let __ret1 = { $e1 };
let __ret2 = match $rx {
$p2 => $e2,
#[allow(unreachable_patterns)]
_ => unreachable!("first pattern matched, second pattern did not"),
};
(__ret1, __ret2)
},
$p2 => {
let __ret2 = { $e2 };
let __ret1 = match $rx {
$p1 => $e1,
#[allow(unreachable_patterns)]
_ => unreachable!("second pattern matched, first pattern did not"),
};
(__ret1, __ret2)
},
#[allow(unreachable_patterns)]
_ => unreachable!("neither first nor second pattern matched"),
}
};
}
16 changes: 16 additions & 0 deletions node/subsystem-util/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,3 +245,19 @@ fn tick_tack_metronome() {
)
});
}

#[test]
fn macro_arbitrary_order() {
let mut vals = vec![Some(15_usize), None];
let (first, second) = arbitrary_order!(vals.pop().unwrap(); Some(fx) => fx; None => 0);
assert_eq!(first, 15_usize);
assert_eq!(second, 0_usize);
}

#[test]
fn macro_arbitrary_order_swapped() {
let mut vals = vec![None, Some(11_usize)];
let (first, second) = arbitrary_order!(vals.pop().unwrap(); Some(fx) => fx; None => 0);
assert_eq!(first, 11_usize);
assert_eq!(second, 0);
}

0 comments on commit 8477d14

Please sign in to comment.