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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
use std::cell::RefCell;
use std::collections::VecDeque;
use std::fmt::Debug;
use std::rc::Rc;
use std::time::{Duration, Instant};

use futures::executor::{LocalPool, LocalSpawner};
use futures::stream::iter;
use futures::task::LocalSpawnExt;
use futures::{pin_mut, Stream, StreamExt};

pub use clock::TestClock;

use crate::dependencies::{guard::Guard, Dependency};
use crate::effects::{scheduler::Reactor, Delay, Effects, Scheduler};
use crate::reducer::Reducer;
use crate::Task;

mod clock;

#[doc = include_str!("README.md")]
pub struct TestStore<State: Reducer>
where
    <State as Reducer>::Action: Debug,
{
    state: Option<State>, // `Option` so that `into_inner` does not break `Drop`
    pool: LocalPool,

    // external polling
    inner: Rc<RefCell<Inner<<State as Reducer>::Action>>>,
    reactor: Guard<Reactor>,
}

impl<State: Reducer> Default for TestStore<State>
where
    State: Default,
    <State as Reducer>::Action: Debug,
{
    fn default() -> Self {
        Self::new(|| State::default())
    }
}

impl<State: Reducer> Drop for TestStore<State>
where
    <State as Reducer>::Action: Debug,
{
    #[track_caller]
    fn drop(&mut self) {
        assert!(
            self.inner.borrow().actions.is_empty(),
            "one or more extra actions were not tested for: {:#?}",
            self.inner
                .borrow_mut()
                .actions
                .drain(..)
                .collect::<Vec<_>>()
        );
    }
}

impl<State: Reducer> TestClock for TestStore<State>
where
    <State as Reducer>::Action: Debug,
{
    fn advance(&mut self, duration: Duration) {
        let mut inner = self.inner.borrow_mut();
        let now = inner.now + duration;
        inner.now = now;
        drop(inner);

        let timer = Dependency::<Reactor>::new();

        loop {
            self.pool.run_until_stalled();
            timer.poll(now);

            if self.pool.try_run_one() == false {
                break;
            }
        }
    }
}

impl<State: Reducer> TestStore<State>
where
    <State as Reducer>::Action: Debug,
{
    /// Creates a new `Store` with its initial state generated by a function.
    pub fn new<F>(with: F) -> Self
    where
        F: (FnOnce() -> State),
    {
        Self::with_initial(with())
    }

    /// Creates a new `Store` with `state` as its initial state.
    pub fn with_initial(state: State) -> Self {
        let pool = LocalPool::new();
        let spawner = pool.spawner();

        Self {
            state: Some(state),
            inner: Inner::new(spawner),
            reactor: Guard::new(Reactor::new()),
            pool,
        }
    }
    /// Calls the `Store`’s [`Reducer`][`crate::Reducer`] with `action` and asserts the
    /// expected state changes.
    #[track_caller]
    pub fn send(&mut self, action: <State as Reducer>::Action, assert: impl FnOnce(&mut State))
    where
        State: Clone + Debug + PartialEq,
        <State as Reducer>::Action: 'static,
    {
        let mut expected = self.state.clone();
        assert(expected.as_mut().unwrap());

        assert!(
            self.inner.borrow().actions.is_empty(),
            "an extra action was received: {:#?}",
            self.inner
                .borrow_mut()
                .actions
                .drain(..)
                .collect::<Vec<_>>()
        );

        self.state
            .as_mut()
            .unwrap()
            .reduce(action, self.inner.clone());
        assert_eq!(self.state, expected);
    }

    /// Checks that the `Store`’s [`Reducer`][`crate::Reducer`] was called with `action`
    /// and asserts the expected state changes.
    #[track_caller]
    pub fn recv(&mut self, action: <State as Reducer>::Action, assert: impl FnOnce(&mut State))
    where
        State: Clone + Debug + PartialEq,
        <State as Reducer>::Action: Debug + PartialEq + 'static,
    {
        let mut expected = self.state.clone();
        assert(expected.as_mut().unwrap());

        let received = self
            .inner
            .borrow_mut()
            .actions
            .pop_front()
            .expect("no action received");
        assert_eq!(received, action);

        self.state
            .as_mut()
            .unwrap()
            .reduce(action, self.inner.clone());
        assert_eq!(self.state, expected);
    }

    /// Waits until all scheduled tasks have completed.
    ///
    /// A timeout should be added to tests calling `wait()` to ensure that it
    /// does not wait forever if there are bugs in the asynchronous tasks.
    /// For example
    ///
    /// - [ntest][ntest] provides a [timeout][timeout] attribute macro, while
    /// - [divan][divan] has a [max_time][max_time] parameter for its bench macro.
    ///
    /// [ntest]: https://crates.io/crates/ntest
    /// [divan]: https://crates.io/crates/divan
    ///
    /// [timeout]: https://docs.rs/ntest/latest/ntest/attr.timeout.html
    /// [max_time]: https://docs.rs/divan/0.1.14/divan/attr.bench.html#max_time
    pub fn wait(&mut self) {
        self.pool.run()
    }

    /// Consumes the `Store` and returns its current `state` value.
    pub fn into_inner(mut self) -> <State as Reducer>::Output
    where
        State: Into<<State as Reducer>::Output>,
    {
        self.state.take().unwrap().into()
    }
}

struct Inner<Action> {
    actions: VecDeque<Action>,
    spawner: LocalSpawner,
    now: Instant,
}

#[doc(hidden)]
impl<Action> Effects for Rc<RefCell<Inner<Action>>>
where
    Action: Debug + 'static,
{
    type Action = Action;

    fn action(&self, action: impl Into<<Self as Effects>::Action>) {
        self.borrow_mut().actions.push_back(action.into());
    }

    fn task<S: Stream<Item = Action> + 'static>(&self, stream: S) -> Task {
        let effects = self.clone();
        let spawner = self.borrow().spawner.clone();

        let handle = spawner
            .spawn_local_with_handle(async move {
                pin_mut!(stream);
                while let Some(action) = stream.next().await {
                    effects.action(action);
                }
            })
            .ok();

        Task { handle, when: None }
    }
}

#[doc(hidden)]
impl<Action> Scheduler for Rc<RefCell<Inner<Action>>>
where
    Action: Debug + 'static,
{
    type Action = Action;

    fn now(&self) -> Instant {
        self.borrow().now
    }

    fn schedule(
        &self,
        action: Self::Action,
        delays: impl IntoIterator<Item = Delay> + 'static,
    ) -> Task
    where
        Self::Action: Clone + 'static,
    {
        self.task(iter(delays).then(move |delay| {
            let action = action.clone();

            async move {
                delay.await;
                action.clone()
            }
        }))
    }
}

impl<Action> Inner<Action> {
    fn new(spawner: LocalSpawner) -> Rc<RefCell<Self>> {
        Rc::new(RefCell::new(Self {
            actions: Default::default(),
            now: Instant::now().into(),
            spawner,
        }))
    }
}