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
/* Copyright 2017 Christopher Bacher
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//! The support library for **[galvanic-mock](https://www.github.com/mindsbackyard/galvanic-mock)**.
//!
//! The crate provides common traits for all mocks generated by **galvanic-mock** as well as data structures for handling the state of mock objects.

#[cfg(feature = "galvanic_assert_integration")] extern crate galvanic_assert;

use std::collections::HashMap;
use std::cell::RefCell;

/// A trait for controlling the behaviour of a mock.
///
/// All mocks generated by `galvanic-mock` implement this trait.
/// The generated mocks use a `MockState` object internally to handle the state of the mock.
/// The mock's implementation of the `MockControl` trait acts as a proxy to the `MockState` object.
pub trait MockControl {
    /// Passing `true` enables verification of expected behaviours when the mock object is dropped.
    ///
    /// See `verify()`.
    fn should_verify_on_drop(&mut self, flag: bool);

    /// For *internal* use only.
    ///
    /// Enables a behaviour defined in a `given!`-block for a trait's method.
    ///
    /// # Arguments
    /// * `requested_trait` - the trait's name
    /// * `method` - the trait's method's name
    /// * `behaviour` - the behaviour to be activated
    fn add_given_behaviour(&self,
                           requested_trait: &'static str,
                           method: &'static str,
                           behaviour: GivenBehaviour);

    /// Deactivates all behaviours activated by a `given!`-block before.
    fn reset_given_behaviours(&mut self);

    /// For *internal* use only.
    ///
    /// Enables a behaviour defined in a `expect_interactions!`-block for a trait's method.
    ///
    /// # Arguments
    /// * `requested_trait` - the trait's name
    /// * `method` - the trait's method's name
    /// * `behaviour` - the behaviour to be activated
    fn add_expect_behaviour(&self,
                            requested_trait: &'static str,
                            method: &'static str,
                            behaviour: ExpectBehaviour);

    /// Deactivates all behaviours activated by a `expect_interactions!`-block before.
    fn reset_expected_behaviours(&mut self);

    /// Returns `true` iff all expected interactions with the mock have occurred.
    fn are_expected_behaviours_satisfied(&self) -> bool;

    /// Panics if some expected interaction with the mock has not occurred.
    ///
    /// An expected interaction is defined by a behaviour added to the mock in an `expect_interactions!`-block.
    /// A behaviour is said to match if the method asocciated with the behaviour is called with values satisfying the behaviour's argument pattern.
    /// A behaviour is satisfied if its expected repetitions are fulfilled.
    ///
    /// Verification should be skipped if the current thread is already panicking.
    /// This method should also be executed once the implementor is drpped if verication on drop is enabled.
    fn verify(&self);
}


/// Stores the state of a mock.
///
/// The state of a mock object is compromised by its enabled *given* and *expected* behaviours.
/// As well as its verification policies.
pub struct MockState {
    /// The enabled *given* behaviours addressed by a tuple of the names of the mocked *trait* and *method*.
    pub given_behaviours: RefCell<HashMap<(&'static str, &'static str), Vec<GivenBehaviour>>>,
    /// The enabled *expected* behaviours addressed by a tuple of the names of the mocked *trait* and *method*.
    pub expect_behaviours: RefCell<HashMap<(&'static str, &'static str), Vec<ExpectBehaviour>>>,
    /// Whether the *expected behaviours should be verfied on drop.
    verify_on_drop: bool,
}

impl MockState {
    pub fn new() -> Self {
        Self {
            given_behaviours: RefCell::new(HashMap::new()),
            expect_behaviours: RefCell::new(HashMap::new()),
            verify_on_drop: true,
        }
    }
}

impl MockControl for MockState {
    fn should_verify_on_drop(&mut self, flag: bool) {
        self.verify_on_drop = flag;
    }

    fn add_given_behaviour(&self,
                           requested_trait: &'static str,
                           method: &'static str,
                           behaviour: GivenBehaviour) {
        self.given_behaviours
            .borrow_mut()
            .entry((requested_trait, method))
            .or_insert_with(|| Vec::new())
            .push(behaviour);
    }

    fn reset_given_behaviours(&mut self) {
        self.given_behaviours.borrow_mut().clear();
    }

    fn add_expect_behaviour(&self,
                            requested_trait: &'static str,
                            method: &'static str,
                            behaviour: ExpectBehaviour) {
        self.expect_behaviours
            .borrow_mut()
            .entry((requested_trait, method))
            .or_insert_with(|| Vec::new())
            .push(behaviour);
    }

    fn reset_expected_behaviours(&mut self) {
        self.expect_behaviours.borrow_mut().clear();
    }

    fn are_expected_behaviours_satisfied(&self) -> bool {
        let mut unsatisfied_messages: Vec<String> = Vec::new();
        for behaviour in self.expect_behaviours.borrow().values().flat_map(|vs| vs) {
            if !behaviour.is_saturated() {
                unsatisfied_messages
                    .push(format!("Behaviour unsatisfied with {} matching invocations: {}",
                                  behaviour.num_matches.get(),
                                  behaviour.describe()));
            }
        }
        if !unsatisfied_messages.is_empty() {
            for message in unsatisfied_messages {
                eprintln!("{}", message);
            }
            false
        } else {
            true
        }
    }

    fn verify(&self) {
        if !std::thread::panicking() && !self.are_expected_behaviours_satisfied() {
            panic!("There are unsatisfied expected behaviours for mocked traits.");
        }
    }
}

impl std::ops::Drop for MockState {
    /// Verfies the *expected interactions* on the mock if the policy is enabled.
    ///
    /// # Panics
    /// iff the verification fails.
    fn drop(&mut self) {
        if self.verify_on_drop {
            self.verify();
        }
    }
}


/// Defines a matcher for the arguments of a mocked method.
///
/// A matcher may check a single argument of a method or all arguments at once.
/// If all arguments are to be checked then they should be passed in a curried form, e.g., as a tuple.
pub trait ArgMatcher<'a, T: 'a> {
    // Returns `true` iff the `actual` arguments satisfy the matcher.
    fn match_args(&self, actual: &'a T) -> bool;
}

/// Any function accepting an argument and returning a `bool` can be used as `ArgMatcher`.
impl<'a, T: 'a, F> ArgMatcher<'a, T> for F
    where F: Fn(&'a T) -> bool
{
    fn match_args(&self, actual: &'a T) -> bool {
        self(actual)
    }
}

/// All matchers of the **galvanic-assert** crate can be used as `ArgMatcher`.
///
/// The crate's matchers can either be used to inspect a single argument or all of them (in curried form).
#[cfg(feature = "galvanic_assert_integration")]
impl<'a, T: 'a> ArgMatcher<'a, T> for Box<::galvanic_assert::Matcher<'a, T> + 'a> {
    fn match_args(&self, actual: &'a T) -> bool {
        self.check(actual).into()
    }
}

/// Stores the state of a *given* behaviour.
pub struct GivenBehaviour {
    /// The unique id of the behaviour within the mocked method to which it belongs.
    pub stmt_id: usize,
    /// How often the behaviour has been matched.
    num_matches: std::cell::Cell<usize>,
    /// How often the behaviour should be matched before it is exhausted, `None` if never.
    expected_matches: Option<usize>,
    /// The bound variables available to the behaviour's `ArgMatcher`.
    pub bound: std::rc::Rc<std::any::Any>,
    /// A string representation of the behaviour's definition.
    stmt_repr: String,
}

impl GivenBehaviour {
    /// Creates a new behaviour which is never exhausted.
    pub fn with(stmt_id: usize, bound: std::rc::Rc<std::any::Any>, stmt_repr: &str) -> Self {
        Self {
            stmt_id: stmt_id,
            num_matches: std::cell::Cell::new(0),
            expected_matches: None,
            bound: bound,
            stmt_repr: stmt_repr.to_string(),
        }
    }

    /// Creates a new behaviour which is never exhausted after being matched `times`.
    pub fn with_times(times: usize,
                      stmt_id: usize,
                      bound: std::rc::Rc<std::any::Any>,
                      stmt_repr: &str)
                      -> Self {
        Self {
            stmt_id: stmt_id,
            num_matches: std::cell::Cell::new(0),
            expected_matches: Some(times),
            bound: bound,
            stmt_repr: stmt_repr.to_string(),
        }
    }

    /// Notifies the behaviour that it has been matched.
    pub fn matched(&self) {
        self.num_matches.set(self.num_matches.get() + 1);
    }

    /// Returns `true` iff the behaviour is exhausted.
    pub fn is_saturated(&self) -> bool {
        match self.expected_matches {
            Some(limit) => self.num_matches.get() >= limit,
            None => false,
        }
    }

    /// Returns a description of the behaviour.
    pub fn describe(&self) -> &str {
        &self.stmt_repr
    }
}


/// Stores the state of a *expected* behaviour.
pub struct ExpectBehaviour {
    /// The unique id of the behaviour within the mocked method to which it belongs.
    pub stmt_id: usize,
    /// How often the behaviour has been matched.
    num_matches: std::cell::Cell<usize>,
    /// The expected minimum number of matches for the behaviour to be satisfied
    expected_min_matches: Option<usize>,
    /// The expected maximum number of matches for the behaviour to be satisfied
    expected_max_matches: Option<usize>,
    #[allow(dead_code)] in_order: Option<bool>,
    /// The bound variables available to the behaviour's `ArgMatcher`.
    pub bound: std::rc::Rc<std::any::Any>,
    /// A string representation of the behaviour's definition.
    stmt_repr: String,
}


impl ExpectBehaviour {
    /// Creates a new behaviour which is satisfied if matched `times`.
    pub fn with_times(times: usize,
                      stmt_id: usize,
                      bound: std::rc::Rc<std::any::Any>,
                      stmt_repr: &str)
                      -> Self {
        Self {
            stmt_id: stmt_id,
            num_matches: std::cell::Cell::new(0),
            expected_min_matches: Some(times),
            expected_max_matches: Some(times),
            in_order: None,
            bound: bound,
            stmt_repr: stmt_repr.to_string(),
        }
    }

    /// Creates a new behaviour which is satisfied if matched `at_least_times`.
    pub fn with_at_least(at_least_times: usize,
                         stmt_id: usize,
                         bound: std::rc::Rc<std::any::Any>,
                         stmt_repr: &str)
                         -> Self {
        Self {
            stmt_id: stmt_id,
            num_matches: std::cell::Cell::new(0),
            expected_min_matches: Some(at_least_times),
            expected_max_matches: None,
            in_order: None,
            bound: bound,
            stmt_repr: stmt_repr.to_string(),
        }
    }

    /// Creates a new behaviour which is satisfied if matched `at_most_times`.
    pub fn with_at_most(at_most_times: usize,
                        stmt_id: usize,
                        bound: std::rc::Rc<std::any::Any>,
                        stmt_repr: &str)
                        -> Self {
        Self {
            stmt_id: stmt_id,
            num_matches: std::cell::Cell::new(0),
            expected_min_matches: None,
            expected_max_matches: Some(at_most_times),
            in_order: None,
            bound: bound,
            stmt_repr: stmt_repr.to_string(),
        }
    }

    /// Creates a new behaviour which is satisfied if matched between `[at_least_times, at_most_times]` (inclusive endpoints).
    pub fn with_between(at_least_times: usize,
                        at_most_times: usize,
                        stmt_id: usize,
                        bound: std::rc::Rc<std::any::Any>,
                        stmt_repr: &str)
                        -> Self {
        Self {
            stmt_id: stmt_id,
            num_matches: std::cell::Cell::new(0),
            expected_min_matches: Some(at_least_times),
            expected_max_matches: Some(at_most_times),
            in_order: None,
            bound: bound,
            stmt_repr: stmt_repr.to_string(),
        }
    }

    /// Notifies the behaviour that it has been matched.
    pub fn matched(&self) {
        self.num_matches.set(self.num_matches.get() + 1);
    }

    /// Returns `true` iff current number of matches would satify the behaviours expected repetitions.
    pub fn is_saturated(&self) -> bool {
        self.expected_min_matches.unwrap_or(0) <= self.num_matches.get() &&
        self.num_matches.get() <= self.expected_max_matches.unwrap_or(std::usize::MAX)
    }

    /// Returns a description of the behaviour.
    pub fn describe(&self) -> &str {
        &self.stmt_repr
    }
}