SHARE
TWEET

Untitled

a guest Apr 18th, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #![allow(dead_code)]
  2. use std::cmp::{Eq, PartialEq};
  3. use std::fmt::Debug;
  4.  
  5. #[macro_export]
  6. macro_rules! assert_contains {
  7.     ($collection:expr, $item:expr) => {
  8.         if let None = $collection.iter().find(|&&x| x == $item) {
  9.             panic!("assertion failed: (collection contains item)\n       item: {:?}\n collection: {:?}\n",
  10.                     $item,
  11.                     $collection,
  12.             );
  13.         }
  14.     };
  15. }
  16.  
  17. #[macro_export]
  18. macro_rules! assert_ok {
  19.     ($result:expr) => {{
  20.         use crate::ChainOk;
  21.         if let Err(_) = $result {
  22.             panic!(
  23.                 "assertion failed: ({0} == Ok(_))\n {0}: {1:?}\n",
  24.                 stringify!($result),
  25.                 $result,
  26.             );
  27.         }
  28.         ChainOk::new($result)
  29.     }};
  30. }
  31.  
  32. struct ChainOk<T>(T);
  33.  
  34. impl<T, E> ChainOk<Result<T, E>>
  35. where
  36.     T: Debug + PartialEq + Eq,
  37. {
  38.     fn new(result: Result<T, E>) -> Self {
  39.         Self(result)
  40.     }
  41.  
  42.     fn with_value(&self, right: T) {
  43.         if let ChainOk(Ok(left)) = &self {
  44.             if *left != right {
  45.                 panic!(
  46.                     "assertion failed: (Ok(left) => left == right)\n  left: {:?}\n right: {:?}\n",
  47.                     *left, right
  48.                 );
  49.             }
  50.         }
  51.     }
  52. }
  53.  
  54. #[cfg(test)]
  55. mod tests {
  56.     #[test]
  57.     fn contains_item() {
  58.         let vec = vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
  59.         let x = 5;
  60.         assert_contains!(vec, x);
  61.     }
  62.  
  63.     #[test]
  64.     fn does_not_contain_item() {
  65.         let vec = vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
  66.         let x = 2;
  67.         assert_contains!(vec, x);
  68.     }
  69.  
  70.     #[test]
  71.     fn result_is_ok_with_correct_inner_value() {
  72.         let result = "5".parse::<u32>();
  73.         assert_ok!(result).with_value(5);
  74.     }
  75.  
  76.     #[test]
  77.     fn result_is_ok_with_wrong_inner_value() {
  78.         let result = "5".parse::<u32>();
  79.         assert_ok!(result).with_value(2);
  80.     }
  81.  
  82.     #[test]
  83.     fn result_is_err() {
  84.         let result = "z".parse::<u32>();
  85.         assert_ok!(result).with_value(5);
  86.     }
  87. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top