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
//! Testing utilities for [thalo](https://docs.rs/thalo) apps.
//!
//! # Examples
//!
//! Create aggregate and events.
//!
//! ```
//! use thalo::{
//!     aggregate::{Aggregate, TypeId},
//!     event::EventType,
//! };
//! use thiserror::Error;
//!
//! #[derive(Aggregate, Clone, Debug, Default, PartialEq, TypeId)]
//! struct BankAccount {
//!     id: String,
//!     opened: bool,
//!     balance: f64,
//! }
//!
//! #[derive(Clone, Debug, EventType)]
//! enum BankAccountEvent {
//!     OpenedAccount { balance: f64 },
//! }
//!
//! fn apply(bank_account: &mut BankAccount, event: BankAccountEvent) {
//!     use BankAccountEvent::*;
//!
//!     match event {
//!         OpenedAccount { balance } => {
//!             bank_account.opened = true;
//!             bank_account.balance = balance;
//!         }
//!     }
//! }
//! ```
//!
//! Test aggregate events.
//!
//! ```
//! # use thalo::{
//! #     aggregate::{Aggregate, TypeId},
//! #     event::EventType,
//! # };
//! # use thiserror::Error;
//! #
//! # #[derive(Aggregate, Clone, Debug, Default, PartialEq, TypeId)]
//! # struct BankAccount {
//! #     id: String,
//! #     opened: bool,
//! #     balance: f64,
//! # }
//! #
//! # #[derive(Clone, Debug, EventType)]
//! # enum BankAccountEvent {
//! #     OpenedAccount { balance: f64 },
//! # }
//! #
//! # fn apply(bank_account: &mut BankAccount, event: BankAccountEvent) {
//! #     use BankAccountEvent::*;
//! #
//! #     match event {
//! #         OpenedAccount { balance } => {
//! #             bank_account.opened = true;
//! #             bank_account.balance = balance;
//! #         }
//! #     }
//! # }
//! #
//! #[cfg(test)]
//! mod tests {
//!     use thalo_testing::*;
//!     use super::{BankAccount, BankAccountEvent};
//!
//!     #[test]
//!     fn opened_account() {
//!         BankAccount::given(
//!             "account-123",
//!             BankAccountEvent::OpenedAccount {
//!                 balance: 0.0,
//!             }
//!         )
//!         .should_eq(BankAccount {
//!             id: "account-123".to_string(),
//!             opened: true,
//!             balance: 0.0,
//!         });
//!     }
//! }
//! ```
//!
//! Test aggregate commands.
//!
//! ```
//! # use thalo::{
//! #     aggregate::{Aggregate, TypeId},
//! #     event::EventType,
//! # };
//! # use thiserror::Error;
//! #
//! # #[derive(Aggregate, Clone, Debug, Default, PartialEq, TypeId)]
//! # struct BankAccount {
//! #     id: String,
//! #     opened: bool,
//! #     balance: f64,
//! # }
//! #
//! # #[derive(Clone, Debug, EventType)]
//! # enum BankAccountEvent {
//! #     OpenedAccount { balance: f64 },
//! # }
//! #
//! # fn apply(bank_account: &mut BankAccount, event: BankAccountEvent) {
//! #     use BankAccountEvent::*;
//! #
//! #     match event {
//! #         OpenedAccount { balance } => {
//! #             bank_account.opened = true;
//! #             bank_account.balance = balance;
//! #         }
//! #     }
//! # }
//! #
//! impl BankAccount {
//!     pub fn open_account(
//!         &self,
//!         initial_balance: f64,
//!     ) -> Result<BankAccountEvent, BankAccountError> {
//!         if self.opened {
//!             return Err(BankAccountError::AlreadyOpened);
//!         }
//!
//!         if initial_balance < 0.0 {
//!             return Err(BankAccountError::NegativeAmount);
//!         }
//!
//!         Ok(BankAccountEvent::OpenedAccount {
//!             balance: initial_balance,
//!         })
//!     }
//! }
//!
//! #[derive(Debug, Error)]
//! pub enum BankAccountError {
//!     #[error("account already opened")]
//!     AlreadyOpened,
//!     #[error("negative amount")]
//!     NegativeAmount,
//! }
//!
//! #[cfg(test)]
//! mod tests {
//!     use thalo_testing::*;
//!     use super::{BankAccount, BankAccountError, BankAccountEvent};
//!
//!     #[test]
//!     fn open_account() {
//!         BankAccount::given_no_events("account-123")
//!             .when(|bank_account| bank_account.open_account(0.0))
//!             .then(Ok(BankAccountEvent::OpenedAccount {
//!                 balance: 0.0,
//!             }));
//!     }

//!     #[test]
//!     fn open_account_already_opened() {
//!         BankAccount::given(
//!             "account-123",
//!             BankAccountEvent::OpenedAccount {
//!                 balance: 0.0,
//!             },
//!         )
//!         .when(|bank_account| bank_account.open_account(50.0))
//!         .then(Err(BankAccountError::AlreadyOpened));
//!     }
//!
//!     #[test]
//!     fn open_account_negative_amount() {
//!         BankAccount::given_no_events()
//!             .when(|bank_account| bank_account.open_account(-10.0))
//!             .then(Err(BankAccountError::NegativeAmount));
//!     }
//! ```

#![deny(missing_docs)]

use std::fmt;

use thalo::aggregate::Aggregate;

/// An aggregate given events.
pub struct GivenTest<A>(A);

/// An aggregate when a command is performed.
pub struct WhenTest<A, R> {
    aggregate: A,
    result: R,
}

/// Given events for an aggregate.
pub trait Given: Aggregate + Sized {
    /// Given a single event for an aggregate.
    fn given(
        id: impl Into<<Self as Aggregate>::ID>,
        event: <Self as Aggregate>::Event,
    ) -> GivenTest<Self> {
        Self::given_events(id, vec![event])
    }

    /// Given events for an aggregate.
    fn given_events(
        id: impl Into<<Self as Aggregate>::ID>,
        events: impl Into<Vec<<Self as Aggregate>::Event>>,
    ) -> GivenTest<Self> {
        let mut aggregate = Self::new(id.into());
        for event in events.into() {
            aggregate.apply(event);
        }
        GivenTest(aggregate)
    }

    /// Given no events for an aggregate.
    fn given_no_events(id: impl Into<<Self as Aggregate>::ID>) -> GivenTest<Self> {
        let aggregate = Self::new(id.into());
        GivenTest(aggregate)
    }
}

impl<A> Given for A where A: Aggregate + Sized {}

impl<A> GivenTest<A>
where
    A: Aggregate,
{
    /// When a command is applied.
    pub fn when<F, R>(mut self, f: F) -> WhenTest<A, R>
    where
        F: FnOnce(&mut A) -> R,
    {
        let result = f(&mut self.0);
        WhenTest {
            aggregate: self.0,
            result,
        }
    }

    /// Given previous events, the aggregate should equal the given state.
    pub fn should_eq<S>(self, state: S) -> Self
    where
        A: fmt::Debug + PartialEq<S>,
        S: fmt::Debug,
    {
        assert_eq!(self.0, state);
        self
    }

    /// Given previous events, the aggregate's state should be unchanged.
    pub fn should_be_unchanged(self) -> Self
    where
        A: fmt::Debug + PartialEq<A>,
        <A as Aggregate>::ID: Clone,
    {
        assert_eq!(self.0, A::new(self.0.id().clone()));
        self
    }
}

impl<A, R> WhenTest<A, R>
where
    A: Aggregate,
{
    /// Get the inner result from the previous when() action.
    pub fn into_result(self) -> R {
        self.result
    }

    /// Get the inner aggregate.
    pub fn into_state(self) -> A {
        self.aggregate
    }

    /// Then the result of the previous when() action should equal the given parameter.
    pub fn then<T>(self, result: T) -> WhenTest<A, R>
    where
        R: fmt::Debug + PartialEq<T>,
        T: fmt::Debug,
    {
        assert_eq!(self.result, result);
        self
    }

    /// Apply result of previous when() action.
    pub fn apply<F, I>(mut self, f: F) -> GivenTest<A>
    where
        F: FnOnce(R) -> I,
        I: IntoIterator<Item = <A as Aggregate>::Event>,
    {
        let events = f(self.result).into_iter();
        for event in events {
            self.aggregate.apply(event);
        }
        GivenTest(self.aggregate)
    }
}

impl<A, R, E> WhenTest<A, Result<R, E>>
where
    A: Aggregate,
{
    /// Then the result of the previous when() action should be Ok(T), with T being equal the given parameter.
    pub fn then_ok<T>(self, result: T) -> WhenTest<A, R>
    where
        T: fmt::Debug,
        R: fmt::Debug,
        E: fmt::Debug,
        Result<R, E>: PartialEq<Result<T, E>>,
    {
        assert_eq!(self.result, Result::<T, E>::Ok(result));
        WhenTest {
            aggregate: self.aggregate,
            result: self.result.unwrap(),
        }
    }

    /// Then the result of the previous when() action should be Err(E), with E being equal the given parameter.
    pub fn then_err<T>(self, result: T) -> GivenTest<A>
    where
        T: fmt::Debug,
        R: fmt::Debug,
        E: fmt::Debug,
        Result<R, E>: PartialEq<Result<R, T>>,
    {
        assert_eq!(self.result, Result::<R, T>::Err(result));
        GivenTest(self.aggregate)
    }
}