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
103
104
105
106
mod array;
#[cfg(feature = "alloc")]
mod boxed;
mod reference;
#[cfg(feature = "async")]
mod sink;
mod slice;
mod tuple;
#[cfg(feature = "async")]
pub use sink::AsyncReactor;
pub trait Reactor<S: ?Sized> {
type Error;
fn react(&mut self, state: &S) -> Result<(), Self::Error>;
}
#[cfg(test)]
mod tests {
use super::*;
use mockall::{predicate::*, *};
use test_strategy::proptest;
mock! {
pub Reactor<T: 'static, E: 'static> {
pub fn id(&self) -> usize;
}
impl<T: 'static, E: 'static> Reactor<T> for Reactor<T, E> {
type Error = E;
fn react(&mut self, state: &T) -> Result<(), E>;
}
impl<T: 'static, E: 'static> Clone for Reactor<T, E> {
fn clone(&self) -> Self;
}
}
#[cfg(feature = "async")]
use futures::Sink;
#[cfg(feature = "async")]
use std::{pin::Pin, task::Context, task::Poll};
#[cfg(feature = "async")]
impl<S: Unpin, E: Unpin> Sink<S> for MockReactor<S, E> {
type Error = E;
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn start_send(self: Pin<&mut Self>, state: S) -> Result<(), Self::Error> {
self.get_mut().react(&state)
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
#[proptest]
fn react(state: u8, result: Result<(), u8>) {
let mut mock = MockReactor::new();
mock.expect_react()
.with(eq(state))
.once()
.return_const(result);
let reactor: &mut dyn Reactor<_, Error = _> = &mut mock;
assert_eq!(reactor.react(&state), result);
}
}
#[cfg(test)]
pub(crate) use self::tests::MockReactor;