table_test/
table.rs

1use std::iter::Iterator;
2use std::vec::IntoIter;
3use std::rc::Rc;
4use std::cell::RefCell;
5use test_case::TestCase;
6use ansi_term::Colour::*;
7
8pub struct Table<I, E> {
9    values: IntoIter<(I, E)>,
10    nb_test_failed: Rc<RefCell<usize>>,
11    nb_of_tests: usize,
12}
13
14impl<I, E> Table<I, E> {
15    pub fn new(values: Vec<(I, E)>) -> Table<I, E> {
16        Table {
17            nb_of_tests: values.len(),
18            values: values.into_iter(),
19            nb_test_failed: Rc::new(RefCell::new(0)),
20        }
21    }
22}
23
24impl<I, E> Drop for Table<I, E> {
25    fn drop(&mut self) {
26        let nb_test_failed = *self.nb_test_failed.borrow();
27        if nb_test_failed > 0 {
28            let header = "\n--------------------\n";
29            let nb_test_passed = Green
30                .bold()
31                .paint(format!("{}", self.nb_of_tests - nb_test_failed));
32            let nb_test_failed = Red.bold().paint(format!("{}", nb_test_failed));
33
34            println!(
35                "{}{} Passed {} Failed\n",
36                header, nb_test_passed, nb_test_failed
37            );
38            panic!("Test Failed");
39        }
40    }
41}
42
43impl<I, E> Iterator for Table<I, E> {
44    type Item = (TestCase, I, E);
45    fn next(&mut self) -> Option<Self::Item> {
46        if let Some(value) = self.values.next() {
47            Some((
48                TestCase::new(Rc::clone(&self.nb_test_failed)),
49                value.0,
50                value.1,
51            ))
52        } else {
53            None
54        }
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    #[should_panic]
64    pub fn given_ugly_names_when_validate_is_beautiful_then_table_panic() {
65        let table = Table::new(vec![
66            ("an ugly name", false),
67            ("a beautiful name", true),
68            ("an amazing name", true),
69            ("worst name ever", false),
70        ]);
71
72        for (test_case, name, expected) in table {
73            test_case
74                .given(name)
75                .when("validate is beautiful")
76                .then(&format!("{}", expected))
77                .assert_eq(expected, true);
78        }
79    }
80
81    #[test]
82    pub fn given_wonderful_names_when_validate_is_beautiful_then_table_dont_panic() {
83        let table = Table::new(vec![("a beautiful name", true), ("an amazing name", true)]);
84
85        for (test_case, name, expected) in table {
86            test_case
87                .given(name)
88                .when("validate is beatifull")
89                .then(&format!("{}", expected))
90                .assert_eq(expected, true);
91        }
92    }
93}