1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
use std::fmt::Debug;
use std::sync::{Arc, Mutex};
#[derive(Debug)]
pub struct Generic<T: Clone + Debug + PartialEq> {
expected: Arc<Mutex<(usize, Vec<T>)>>,
}
impl<'a, T: 'a> Generic<T>
where
T: Clone + Debug + PartialEq,
{
pub fn new<E>(expected: E) -> Generic<T>
where
E: IntoIterator<Item = &'a T>,
{
let mut g = Generic {
expected: Arc::new(Mutex::new((0, vec![]))),
};
g.expect(expected);
g
}
pub fn expect<E>(&mut self, expected: E)
where
E: IntoIterator<Item = &'a T>,
{
let v: Vec<T> = expected.into_iter().map(|v| v.clone()).collect();
let mut e = self.expected.lock().unwrap();
e.0 = 0;
e.1 = v;
}
pub fn done(&mut self) {
let e = self.expected.lock().unwrap();
assert_eq!(
e.0,
e.1.len(),
"Mock call number(left) and expectations(right) do not match"
);
}
}
impl<T> Clone for Generic<T>
where
T: Clone + Debug + PartialEq,
{
fn clone(&self) -> Self {
Generic {
expected: self.expected.clone(),
}
}
}
impl<T> Iterator for Generic<T>
where
T: Clone + Debug + PartialEq,
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
let mut e = self.expected.lock().unwrap();
e.0 += 1;
e.1.get(e.0 - 1).map(|v| v.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_generic_mock() {
let expectations = [0u8, 1u8];
let mut mock: Generic<u8> = Generic::new(&expectations);
assert_eq!(mock.next(), Some(0u8));
assert_eq!(mock.next(), Some(1u8));
assert_eq!(mock.next(), None);
}
}