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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
use crate::tester::*;
use crate::{artifact::JsonTrace, TestError};
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value as JsonValue;
use std::iter::Iterator;
use std::{any::Any, fmt::Debug, panic::UnwindSafe};

/// A trait for handling the mapping between abstract and concrete system states
/// It is supposed that the tests are described in terms of a
/// (much simpler) abstract state,
/// with a lot less components than the concrete system state being tested.
///
/// A concrete system state can be partitioned into several state subspaces,
/// With separate abstract state describing each concrete state subspace.
#[allow(unused_variables)]
pub trait StateHandler<State> {
    /// Initialize concrete state from the abstract one.
    /// Should completely reinitialize the concrete state when called.
    /// Guaranteed to be called at the beginning of each test.
    fn init(&mut self, state: State);

    /// Read the concrete state into the abstract one.
    fn read(&self) -> State;
}

/// A trait for handling abstract test actions (messages).
pub trait ActionHandler<Action> {
    /// Type of action outcome. Set to () if none.
    type Outcome;

    /// Initialize processing of actions of that type.
    /// Guaranteed to be called at the beginning of each test
    fn init(&mut self) {}

    /// Process an action of that type & modify the concrete state as appropriate.
    /// The test produces the outcome, which may be checked later.
    fn handle(&mut self, action: Action) -> Self::Outcome;
}

/// A set of events to describe tests based on abstract states and actions.
#[derive(Debug)]
pub enum Event {
    /// Initialize the concrete system state from the abstract one.
    Init(Box<dyn Any>),
    /// Process the abstract action, modifying the system state.
    Action(Box<dyn Any>),
    /// Expect the provided outcome of the last action.
    Expect(String),
    /// Check the assertion about the abstract system state.
    Check(Box<dyn Any>),
    /// Expect exactly the provided abstract system state.
    Equal(Box<dyn Any>),
}

/// A stream of events; defines the test.
#[derive(Debug)]
pub struct EventStream {
    events: Vec<Event>,
}

impl Default for EventStream {
    fn default() -> Self {
        EventStream::new()
    }
}

impl EventStream {
    /// Create a new event stream.
    pub fn new() -> EventStream {
        EventStream { events: vec![] }
    }

    /// Add an initial abstract state to the event stream.
    /// [StateHandler::init] should handle this event and
    /// initialize the concrete system state from it.
    /// Modifies the caller.
    pub fn add_init<T>(&mut self, state: T)
    where
        T: 'static,
    {
        self.events.push(Event::Init(Box::new(state)));
    }

    /// Add an initial abstract state to the event stream.
    /// [StateHandler::init] should handle this event and
    /// initialize the concrete system state from it.
    /// Produces the modified version of the caller,
    /// allowing to chain the events.
    pub fn init<T>(mut self, state: T) -> Self
    where
        T: 'static,
    {
        self.add_init(state);
        self
    }

    /// Add an abstract action to the event stream.
    /// [ActionHandler::handle] should handle the action and
    /// modify the concrete system state accordingly.
    /// Modifies the caller.
    pub fn add_action<T>(&mut self, action: T)
    where
        T: 'static,
    {
        self.events.push(Event::Action(Box::new(action)));
    }

    /// Add an abstract action to the event stream.
    /// [ActionHandler::handle] should handle the action and
    /// modify the concrete system state accordingly.
    /// Produces the modified version of the caller,
    /// allowing to chain the events.
    pub fn action<T>(mut self, action: T) -> Self
    where
        T: 'static,
    {
        self.add_action(action);
        self
    }

    /// Add the check for the previous action outcome to the event stream.
    /// [ActionHandler::handle] to which the previous actions was dispatched,
    /// should produce exactly this outcome.
    /// Modifies the caller.
    pub fn add_expect<T>(&mut self, outcome: T)
    where
        T: 'static + Serialize,
    {
        self.events.push(Event::Expect(
            serde_json::to_string_pretty(&outcome).unwrap(),
        ));
    }

    /// Add the check for the previous action outcome to the event stream.
    /// [ActionHandler::handle] to which the previous actions was dispatched,
    /// should produce exactly this outcome.
    /// Produces the modified version of the caller,
    /// allowing to chain the events.
    pub fn expect<T>(mut self, outcome: T) -> Self
    where
        T: 'static + Serialize,
    {
        self.add_expect(outcome);
        self
    }

    /// Add the assertion about the abstract system state to the event stream.
    /// The check is executed against the state returned by [StateHandler::read].
    /// Modifies the caller.
    pub fn add_check<T>(&mut self, assertion: fn(T))
    where
        T: 'static,
    {
        self.events.push(Event::Check(Box::new(assertion)));
    }

    /// Add the assertion about the abstract system state to the event stream.
    /// The check is executed against the state returned by [StateHandler::read].
    /// Produces the modified version of the caller,
    /// allowing to chain the events.
    pub fn check<T>(mut self, assertion: fn(T)) -> Self
    where
        T: 'static,
    {
        self.add_check(assertion);
        self
    }

    /// Add the expectation about the abstract system state to the event stream.
    /// The abstract state returned by [StateHandler::read] should exactly match.
    /// Modifies the caller.
    pub fn add_equal<T>(&mut self, state: T)
    where
        T: 'static,
    {
        self.events.push(Event::Equal(Box::new(state)));
    }

    /// Add the expectation about the abstract system state to the event stream.
    /// The abstract state returned by [StateHandler::read] should exactly match.
    /// Modifies the caller.
    /// Produces the modified version of the caller,
    /// allowing to chain the events.
    pub fn equal<T>(mut self, state: T) -> Self
    where
        T: 'static,
    {
        self.add_equal(state);
        self
    }
}

impl IntoIterator for EventStream {
    type Item = Event;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.events.into_iter()
    }
}

impl From<JsonTrace> for EventStream {
    fn from(trace: JsonTrace) -> Self {
        let mut events = EventStream::new();
        for (index, value) in trace.into_iter().enumerate() {
            if index == 0 {
                events.add_init(value);
            } else {
                if let JsonValue::Object(value) = value.clone() {
                    if let Some(action) = value.get("action") {
                        events.add_action(action.clone());
                    };
                    if let Some(outcome) = value.get("actionOutcome") {
                        events.add_expect(outcome.clone());
                    }
                }
                events.add_equal(value);
            }
        }
        events
    }
}

/// A runner that allows to run tests specified as event streams
/// against the given concrete system.
/// You can implement several instances of [StateHandler]s
/// and [ActionHandler]s for the `System`, thus allowing your system
/// to handle several kinds of abstract states or actions.
pub struct EventRunner<System: Debug> {
    inits: SystemTester<System>,
    actions: SystemTester<System>,
    checks: SystemTester<System>,
    equals: SystemTester<System>,
    outcome: String,
}

impl<System: Debug> Default for EventRunner<System> {
    fn default() -> Self {
        EventRunner::new()
    }
}

impl<System: Debug> EventRunner<System> {
    /// Create a new runner for the given `System`.
    pub fn new() -> Self {
        EventRunner {
            inits: SystemTester::new(),
            actions: SystemTester::new(),
            checks: SystemTester::new(),
            equals: SystemTester::new(),
            outcome: String::new(),
        }
    }

    /// Equip the runner with the ability to handle given abstract `State`.
    pub fn with_state<State>(mut self) -> Self
    where
        State: 'static + DeserializeOwned + UnwindSafe + Clone + Debug + PartialEq,
        System: 'static + StateHandler<State>,
    {
        self.inits.add(StateHandler::<State>::init);
        self.checks
            .add_fn(|system, assertion: fn(State)| assertion(system.read()));
        self.equals
            .add(|system, state: State| assert_eq!(system.read(), state));
        self
    }

    /// Equip the runner with the ability to handle given abstract `Action`.
    pub fn with_action<Action>(mut self) -> Self
    where
        Action: 'static + DeserializeOwned + UnwindSafe + Clone,
        System: 'static + ActionHandler<Action>,
        <System as ActionHandler<Action>>::Outcome: 'static + Serialize,
    {
        self.actions.add(ActionHandler::<Action>::handle);
        self
    }

    /// Run the runner on:
    /// - the given concrete `system`,
    ///   which provides storage of concrete system states,
    ///   as well as the handling of the abstract states and actions;
    /// - the given stream of events, representing the test.
    ///
    /// Returns the test result.
    pub fn run(
        &mut self,
        system: &mut System,
        stream: &mut dyn Iterator<Item = Event>,
    ) -> Result<(), TestError> {
        // TODO: check that all inits for states are called
        // TODO: call inits for all actions
        for event in stream {
            let result = match event {
                Event::Init(input) => self.inits.test(system, &input),
                Event::Action(input) => self.actions.test(system, &input),
                Event::Expect(expected) => {
                    if self.outcome == expected {
                        TestResult::Success(self.outcome.clone())
                    } else {
                        TestResult::Failure {
                            message: format!(
                                "Expected action outcome '{}', got '{}'",
                                expected, self.outcome
                            ),
                            location: String::new(),
                        }
                    }
                }
                Event::Check(assertion) => self.checks.test(system, &assertion),
                Event::Equal(state) => self.equals.test(system, &state),
            };
            match result {
                TestResult::Success(res) => self.outcome = res,
                TestResult::Failure { message, location } => {
                    return Err(TestError::FailedTest {
                        message,
                        location,
                        test: "".to_string(), // we don't know the test at that point
                        system: format!("{:?}", system),
                    });
                }
                TestResult::Unhandled => {
                    return Err(TestError::UnhandledTest {
                        test: "".to_string(), // we don't know the test at that point
                        system: format!("{:?}", system),
                    });
                }
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::artifact::JsonTrace;
    use serde::{Deserialize, Serialize};
    use serde_json::Value;

    #[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
    struct State1 {
        state1: String,
    }

    #[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
    struct State2 {
        state2: String,
    }

    #[derive(Deserialize, Serialize, Clone)]
    struct Action1 {
        value1: String,
    }

    #[derive(Serialize)]
    enum Outcome {
        Success(String),
        Failure(String),
    }

    #[derive(Deserialize, Serialize, Clone)]
    struct Action2 {
        value2: String,
    }

    #[derive(Debug, Default)]
    struct MySystem {
        state1: String,
        state2: String,
    }

    impl StateHandler<State1> for MySystem {
        fn init(&mut self, state: State1) {
            self.state1 = state.state1;
        }

        fn read(&self) -> State1 {
            State1 {
                state1: self.state1.clone(),
            }
        }
    }

    impl StateHandler<State2> for MySystem {
        fn init(&mut self, state: State2) {
            self.state2 = state.state2;
        }

        fn read(&self) -> State2 {
            State2 {
                state2: self.state2.clone(),
            }
        }
    }

    impl ActionHandler<Action1> for MySystem {
        type Outcome = Outcome;

        fn handle(&mut self, action: Action1) -> Outcome {
            self.state1 = action.value1;
            Outcome::Success("OK".to_string())
        }
    }

    impl ActionHandler<Action2> for MySystem {
        type Outcome = Outcome;

        fn handle(&mut self, action: Action2) -> Outcome {
            self.state2 = action.value2;
            Outcome::Failure("NOT OK".to_string())
        }
    }

    #[test]
    fn test_stream() {
        let events = EventStream::new()
            .init(State1 {
                state1: "init state 1".to_string(),
            })
            .init(State2 {
                state2: "init state 2".to_string(),
            })
            .action(Action1 {
                value1: "action1 state".to_string(),
            })
            .expect(Outcome::Success("OK".to_string()))
            .action(Action2 {
                value2: "action2 state".to_string(),
            })
            .expect(Outcome::Failure("NOT OK".to_string()))
            .check(|state: State1| assert!(state.state1 == "action1 state"))
            .equal(State2 {
                state2: "action2 state".to_string(),
            });

        let mut runner = EventRunner::new()
            .with_state::<State1>()
            .with_state::<State2>()
            .with_action::<Action1>()
            .with_action::<Action2>();

        let mut system = MySystem::default();
        let result = runner.run(&mut system, &mut events.into_iter());
        assert!(result.is_ok());
    }

    #[test]
    fn test_json_trace() {
        let mut system = MySystem::default();
        let mut runner = EventRunner::new()
            .with_state::<State1>()
            .with_state::<State2>()
            .with_action::<Action1>()
            .with_action::<Action2>();

        // Unknown action with value3 field
        let trace: JsonTrace = vec![
            r#"{ "state1": "init state 1", "state2": "init state 2" }"#,
            r#"{ "action": { "value3": "action1 state" },
                 "state1": "action1 state", "state2": "init state 2" }"#,
        ]
        .into_iter()
        .map(|x| serde_json::from_str(x).unwrap())
        .collect::<Vec<Value>>()
        .into();

        let events: EventStream = trace.into();
        let result = runner.run(&mut system, &mut events.into_iter());
        assert!(matches!(result, Err(TestError::UnhandledTest { .. })));

        let trace: JsonTrace = vec![
            r#"{ "state1": "init state 1", "state2": "init state 2" }"#,
            r#"{ "action": { "value1": "action1 state" },
                 "actionOutcome": { "Success": "OK" },
                 "state1": "action1 state", "state2": "init state 2" }"#,
            r#"{ "action": { "value2": "action2 state" },
                 "actionOutcome": { "Failure": "NOT OK" },
                 "state1": "action1 state", "state2": "action2 state" }"#,
        ]
        .into_iter()
        .map(|x| serde_json::from_str(x).unwrap())
        .collect::<Vec<Value>>()
        .into();

        let events: EventStream = trace.into();
        let result = runner.run(&mut system, &mut events.into_iter());
        assert!(result.is_ok());
    }
}