Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![allow(dead_code)]
- use std::cmp::{Eq, PartialEq};
- use std::fmt::Debug;
- #[macro_export]
- macro_rules! assert_contains {
- ($collection:expr, $item:expr) => {
- if let None = $collection.iter().find(|&&x| x == $item) {
- panic!("assertion failed: (collection contains item)\n item: {:?}\n collection: {:?}\n",
- $item,
- $collection,
- );
- }
- };
- }
- #[macro_export]
- macro_rules! assert_ok {
- ($result:expr) => {{
- use crate::ChainOk;
- if let Err(_) = $result {
- panic!(
- "assertion failed: ({0} == Ok(_))\n {0}: {1:?}\n",
- stringify!($result),
- $result,
- );
- }
- ChainOk::new($result)
- }};
- }
- struct ChainOk<T>(T);
- impl<T, E> ChainOk<Result<T, E>>
- where
- T: Debug + PartialEq + Eq,
- {
- fn new(result: Result<T, E>) -> Self {
- Self(result)
- }
- fn with_value(&self, right: T) {
- if let ChainOk(Ok(left)) = &self {
- if *left != right {
- panic!(
- "assertion failed: (Ok(left) => left == right)\n left: {:?}\n right: {:?}\n",
- *left, right
- );
- }
- }
- }
- }
- #[cfg(test)]
- mod tests {
- #[test]
- fn contains_item() {
- let vec = vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
- let x = 5;
- assert_contains!(vec, x);
- }
- #[test]
- fn does_not_contain_item() {
- let vec = vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
- let x = 2;
- assert_contains!(vec, x);
- }
- #[test]
- fn result_is_ok_with_correct_inner_value() {
- let result = "5".parse::<u32>();
- assert_ok!(result).with_value(5);
- }
- #[test]
- fn result_is_ok_with_wrong_inner_value() {
- let result = "5".parse::<u32>();
- assert_ok!(result).with_value(2);
- }
- #[test]
- fn result_is_err() {
- let result = "z".parse::<u32>();
- assert_ok!(result).with_value(5);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement