fnmock 0.3.0

A Rust mocking framework for standalone functions and methods in an impl block.
Documentation
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! An order calls have to be made in, possibly spanning several spied functions.

use std::{cell::RefCell, rc::Rc};

use crate::spy::{
    call_range::CallRange,
    expectation::{DynExpectation, Expectation},
    matcher::Matcher,
};

/// An order the calls matching its expectations have to be made in.
///
/// A sequence is created by the test and handed to as many expectations as it should order.
/// Those expectations may belong to different spied functions, which is the point: a sequence
/// is the only way to say that one function has to be called before another.
///
/// ```ignore
/// let seq = Sequence::new();
/// get_user_spy().expect(eq(2)).times(3).in_sequence(&seq);
/// save_user_spy().expect(eq(2)).once().in_sequence(&seq);
/// ```
///
/// Cloning a sequence — which `in_sequence` does — shares it, so every spy taking part in it
/// sees the same progress. A test may use as many independent sequences as it likes.
///
/// Matching is **greedy**: the current step consumes every call it accepts, and the sequence
/// only moves on once a call arrives that a later step accepts instead. Moving on requires
/// every step in between to be *advancable*, meaning the minimum of its call range is reached.
///
/// A call the sequence cannot place — one no step accepts, or one that would need it to move
/// past a step that is not advancable yet — is none of this sequence's business and leaves it
/// untouched. That is what lets a sequence ignore the calls of a function it does not order,
/// the calls meant for another sequence, and the calls of expectations set outside any
/// sequence. The order is still enforced, just at the end: a step that was passed over never
/// got its calls, so the assert fails.
///
/// A [`Sequence::new_strict`] sequence does not let the second case pass. A call matching a later
/// step while an earlier one is unfinished panics right there, which pins down calls in the
/// wrong order more reliably.
#[derive(Clone)]
pub struct Sequence(Rc<RefCell<SequenceState>>);

struct SequenceState {
    steps: Vec<Box<dyn DynExpectation>>,
    current_step: usize,
    strict: bool,
}

impl Sequence {
    /// Create a sequence without any steps.
    pub fn new() -> Self {
        Self(Rc::new(RefCell::new(SequenceState {
            steps: Vec::new(),
            current_step: 0,
            strict: false,
        })))
    }

    /// Make this sequence panic on a call that matches a later step while an earlier one has
    /// not reached the minimum of its call range yet.
    pub fn new_strict() -> Self {
        Self(Rc::new(RefCell::new(SequenceState {
            steps: Vec::new(),
            current_step: 0,
            strict: true,
        })))
    }

    /// Identity of the shared state, so a spy can tell two clones of one sequence apart from
    /// two different sequences.
    pub(crate) fn id(&self) -> *const () {
        Rc::as_ptr(&self.0).cast::<()>()
    }

    pub(crate) fn append_expectation<M: Matcher>(&mut self, expectation: Expectation<M>) {
        self.0.borrow_mut().steps.push(Box::new(expectation));
    }

    /// Offer one call of a spied function to the sequence.
    ///
    /// # Panics
    ///
    /// A [`Sequence::new_strict`] sequence panics if the call belongs to a later step while an
    /// earlier one has not reached the minimum of its call range yet.
    pub(crate) fn record_call<M: Matcher>(&self, params: &M::Params<'_>) {
        let mut state = self.0.borrow_mut();

        // Greedy: the earliest step from the current one on that accepts the call gets it, even
        // if a later, more specific step would have accepted it too.
        // Position is short-circuiting, so it stops after the first match.
        let Some(offset) = state.steps[state.current_step..]
            .iter()
            .position(|expectation| {
                // In a sequence may be Expectations for different functions / matchers.
                // If downcast_ref returns None the expectation is for a different function.
                if let Some(expectation) = expectation.as_any().downcast_ref::<Expectation<M>>() {
                    expectation.matches(params)
                } else {
                    false
                }
            })
        else {
            return;
        };

        let matched_step = state.current_step + offset;

        let blocked_steps: Vec<usize> = state.steps[state.current_step..matched_step]
            .iter()
            .enumerate()
            .filter_map(|(i, step)| {
                if !step.is_advancable() {
                    Some(state.current_step + i)
                } else {
                    None
                }
            })
            .collect();

        if !blocked_steps.is_empty() {
            if state.strict {
                let details = blocked_steps
                    .iter()
                    .map(|&idx| {
                        let step = &state.steps[idx];
                        format!(
                            "{} ({} of {} calls)",
                            step.describe(),
                            step.call_count(),
                            step.call_range()
                        )
                    })
                    .collect::<Vec<_>>()
                    .join("; ");
                panic!(
                    "Call out of sequence: the call matched {}, but {} not reached its minimum yet: {}",
                    state.steps[matched_step].describe(),
                    if blocked_steps.len() == 1 {
                        "an earlier step has"
                    } else {
                        "earlier steps have"
                    },
                    details
                );
            }
            // Not a call this sequence can take yet, so it is treated like any other call that
            // does not apply to the current step.
            return;
        }

        state.current_step = matched_step;
        state.steps[matched_step].record_match();
    }

    /// Every step belonging to matcher type `M` that has not reached its call range, as
    /// `(description, call_count, call_range)`. `description` names both the expectation and
    /// the spied function it belongs to (see [`Expectation::describe`]), so a failure built
    /// from it never depends on surrounding context to say which function it is about.
    ///
    /// Steps of other functions taking part in this sequence are silently skipped, the same
    /// way [`Sequence::record_call`] only ever matches its own function's steps.
    pub(crate) fn unfulfilled_steps<M: Matcher>(&self) -> Vec<(String, usize, CallRange)> {
        self.0
            .borrow()
            .steps
            .iter()
            .filter_map(|step| step.as_any().downcast_ref::<Expectation<M>>())
            .filter(|expectation| !expectation.is_fulfilled())
            .map(|expectation| {
                (
                    expectation.describe(),
                    expectation.call_count(),
                    expectation.call_range(),
                )
            })
            .collect()
    }

    /// Remove all steps of matcher type `M` from this sequence.
    pub(crate) fn clear_expectations_for<M: Matcher>(&mut self) {
        let mut guard = self.0.borrow_mut();

        let current_step = guard.current_step;

        // Only removed steps before the current one shift it back; later ones don't affect it.
        let remove_before_current_count = guard.steps[..current_step.min(guard.steps.len())]
            .iter()
            .filter(|step| step.as_any().downcast_ref::<Expectation<M>>().is_some())
            .count();

        guard
            .steps
            .retain(|step| step.as_any().downcast_ref::<Expectation<M>>().is_none());

        guard.current_step = current_step - remove_before_current_count;
    }
}

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

#[cfg(test)]
mod tests {
    use std::fmt::Display;

    use super::*;

    #[derive(Clone)]
    struct IntMatcher(i32);

    impl Display for IntMatcher {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "eq({})", self.0)
        }
    }

    impl Matcher for IntMatcher {
        type Params<'a> = (&'a i32,);

        fn matches(&self, params: &Self::Params<'_>) -> bool {
            params.0 == &self.0
        }
    }

    #[derive(Clone)]
    struct StrMatcher(&'static str);

    impl Display for StrMatcher {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "eq({:?})", self.0)
        }
    }

    impl Matcher for StrMatcher {
        type Params<'a> = (&'a str,);

        fn matches(&self, params: &Self::Params<'_>) -> bool {
            params.0 == self.0
        }
    }

    fn int_step(value: i32, function_name: &str) -> Expectation<IntMatcher> {
        Expectation::new(IntMatcher(value), function_name)
    }

    fn record_int(seq: &Sequence, value: i32) {
        seq.record_call::<IntMatcher>(&(&value,));
    }

    fn record_str(seq: &Sequence, value: &str) {
        seq.record_call::<StrMatcher>(&(value,));
    }

    #[test]
    fn calls_in_order_fulfill_every_step() {
        let mut seq = Sequence::new();
        seq.append_expectation(int_step(1, "f"));
        seq.append_expectation(int_step(2, "f"));

        record_int(&seq, 1);
        record_int(&seq, 2);

        assert!(seq.unfulfilled_steps::<IntMatcher>().is_empty());
    }

    #[test]
    fn earliest_matching_step_consumes_the_call_greedily() {
        let mut seq = Sequence::new();
        seq.append_expectation(int_step(1, "f"));
        seq.append_expectation(int_step(1, "f"));

        record_int(&seq, 1);
        record_int(&seq, 1);

        let unfulfilled = seq.unfulfilled_steps::<IntMatcher>();
        assert_eq!(unfulfilled.len(), 1);
        assert_eq!(unfulfilled[0].1, 0);
    }

    #[test]
    fn step_advances_once_its_minimum_call_count_is_reached() {
        let mut seq = Sequence::new();
        let mut first = int_step(1, "f");
        first.set_call_range((2..).into());
        seq.append_expectation(first);
        seq.append_expectation(int_step(2, "f"));

        record_int(&seq, 1);
        record_int(&seq, 1);
        record_int(&seq, 2);

        assert!(seq.unfulfilled_steps::<IntMatcher>().is_empty());
    }

    #[test]
    fn lenient_sequence_ignores_a_call_that_would_skip_an_unfinished_step() {
        let mut seq = Sequence::new();
        let mut first = int_step(1, "f");
        first.set_call_range((2..).into());
        seq.append_expectation(first);
        seq.append_expectation(int_step(2, "f"));

        record_int(&seq, 1);
        record_int(&seq, 2);

        let unfulfilled = seq.unfulfilled_steps::<IntMatcher>();
        assert_eq!(unfulfilled.len(), 2);
        assert_eq!(unfulfilled[0].1, 1);
        assert_eq!(unfulfilled[1].1, 0);
    }

    #[test]
    #[should_panic(expected = "Call out of sequence")]
    fn strict_sequence_panics_when_a_call_would_skip_an_unfinished_step() {
        let mut seq = Sequence::new_strict();
        let mut first = int_step(1, "f");
        first.set_call_range((2..).into());
        seq.append_expectation(first);
        seq.append_expectation(int_step(2, "f"));

        record_int(&seq, 1);
        record_int(&seq, 2);
    }

    #[test]
    #[should_panic(expected = "Too many calls of the spied function")]
    fn calling_a_never_step_panics() {
        let mut seq = Sequence::new();
        let mut never = int_step(1, "f");
        never.set_call_range(0.into());
        seq.append_expectation(never);

        record_int(&seq, 1);
    }

    #[test]
    fn never_step_is_skipped_automatically() {
        let mut seq = Sequence::new();
        let mut never = int_step(1, "f");
        never.set_call_range(0.into());
        seq.append_expectation(never);
        seq.append_expectation(int_step(2, "f"));

        record_int(&seq, 2);

        assert!(seq.unfulfilled_steps::<IntMatcher>().is_empty());
    }

    #[test]
    fn last_step_keeps_accumulating_matching_calls_once_current() {
        let mut seq = Sequence::new();
        let mut last = int_step(1, "f");
        last.set_call_range(5.into());
        seq.append_expectation(last);

        record_int(&seq, 1);
        record_int(&seq, 1);
        record_int(&seq, 1);

        let unfulfilled = seq.unfulfilled_steps::<IntMatcher>();
        assert_eq!(unfulfilled.len(), 1);
        let (description, call_count, call_range) = &unfulfilled[0];
        assert_eq!(*call_count, 3);
        assert!(description.contains("'f'"));
        assert_eq!(call_range.to_string(), CallRange::from(5).to_string());
    }

    #[test]
    #[should_panic(expected = "Too many calls of the spied function")]
    fn exceeding_a_steps_call_range_panics() {
        let mut seq = Sequence::new();
        let mut step = int_step(1, "f");
        step.set_call_range(1.into());
        seq.append_expectation(step);

        record_int(&seq, 1);
        record_int(&seq, 1);
    }

    #[test]
    fn call_matching_no_step_is_ignored() {
        let mut seq = Sequence::new();
        seq.append_expectation(int_step(1, "f"));

        record_int(&seq, 99);

        let unfulfilled = seq.unfulfilled_steps::<IntMatcher>();
        assert_eq!(unfulfilled.len(), 1);
        assert_eq!(unfulfilled[0].1, 0);
    }

    #[test]
    fn orders_calls_across_different_spied_functions() {
        let mut seq = Sequence::new();
        seq.append_expectation(int_step(1, "get_user"));
        seq.append_expectation(Expectation::new(StrMatcher("bob"), "save_user"));

        record_int(&seq, 1);
        record_str(&seq, "bob");

        assert!(seq.unfulfilled_steps::<IntMatcher>().is_empty());
        assert!(seq.unfulfilled_steps::<StrMatcher>().is_empty());
    }

    #[test]
    #[should_panic(expected = "Call out of sequence")]
    fn strict_sequence_panics_on_out_of_order_call_across_functions() {
        let mut seq = Sequence::new_strict();
        let mut first = int_step(1, "get_user");
        first.set_call_range((2..).into());
        seq.append_expectation(first);
        seq.append_expectation(Expectation::new(StrMatcher("bob"), "save_user"));

        record_int(&seq, 1);
        record_str(&seq, "bob");
    }

    #[test]
    fn unfulfilled_steps_only_reports_the_requested_matcher_type() {
        let mut seq = Sequence::new();
        seq.append_expectation(int_step(1, "get_user"));
        seq.append_expectation(Expectation::new(StrMatcher("bob"), "save_user"));

        assert_eq!(seq.unfulfilled_steps::<IntMatcher>().len(), 1);
        assert_eq!(seq.unfulfilled_steps::<StrMatcher>().len(), 1);
    }

    #[test]
    fn default_sequence_is_lenient_not_strict() {
        let mut seq = Sequence::default();
        let mut first = int_step(1, "f");
        first.set_call_range((2..).into());
        seq.append_expectation(first);
        seq.append_expectation(int_step(2, "f"));

        record_int(&seq, 1);
        record_int(&seq, 2);

        assert_eq!(seq.unfulfilled_steps::<IntMatcher>().len(), 2);
    }

    #[test]
    fn clone_shares_the_same_underlying_state() {
        let seq = Sequence::new();
        let clone = seq.clone();
        assert_eq!(seq.id(), clone.id());

        let other = Sequence::new();
        assert_ne!(seq.id(), other.id());
    }

    #[test]
    fn clone_observes_calls_recorded_through_the_original() {
        let mut seq = Sequence::new();
        seq.append_expectation(int_step(1, "f"));
        let clone = seq.clone();

        record_int(&seq, 1);

        assert!(clone.unfulfilled_steps::<IntMatcher>().is_empty());
    }

    #[test]
    fn unfulfilled_steps_reports_no_step_when_every_unfulfilled_step_is_of_a_different_matcher_type()
     {
        let mut seq = Sequence::new();
        seq.append_expectation(Expectation::new(StrMatcher("bob"), "save_user"));
        seq.append_expectation(int_step(1, "f"));

        record_str(&seq, "bob");

        assert!(seq.unfulfilled_steps::<StrMatcher>().is_empty());
        assert!(!seq.unfulfilled_steps::<IntMatcher>().is_empty());
    }

    #[test]
    fn clear_expectations_for_removes_only_that_matcher_types_steps() {
        let mut seq = Sequence::new();
        seq.append_expectation(int_step(1, "f"));
        seq.append_expectation(Expectation::new(StrMatcher("bob"), "g"));

        seq.clear_expectations_for::<IntMatcher>();

        assert!(seq.unfulfilled_steps::<IntMatcher>().is_empty());
        assert_eq!(seq.unfulfilled_steps::<StrMatcher>().len(), 1);
    }

    #[test]
    fn clear_expectations_for_is_a_noop_when_no_steps_of_that_type_exist() {
        let mut seq = Sequence::new();
        seq.append_expectation(Expectation::new(StrMatcher("bob"), "g"));

        seq.clear_expectations_for::<IntMatcher>();

        assert_eq!(seq.unfulfilled_steps::<StrMatcher>().len(), 1);
    }

    #[test]
    fn clear_expectations_for_on_an_empty_sequence_does_nothing() {
        let mut seq = Sequence::new();

        seq.clear_expectations_for::<IntMatcher>();

        assert!(seq.unfulfilled_steps::<IntMatcher>().is_empty());
    }

    #[test]
    fn clear_expectations_for_stops_the_cleared_type_from_blocking_the_sequence() {
        let mut seq = Sequence::new_strict();
        let mut blocking = int_step(1, "f");
        blocking.set_call_range((2..).into());
        seq.append_expectation(blocking);
        seq.append_expectation(Expectation::new(StrMatcher("bob"), "g"));

        seq.clear_expectations_for::<IntMatcher>();

        // Would panic with "Call out of sequence" if the int step still blocked the sequence.
        record_str(&seq, "bob");

        assert!(seq.unfulfilled_steps::<StrMatcher>().is_empty());
    }

    #[test]
    fn clear_expectations_for_does_not_disturb_current_step_for_types_still_present() {
        let mut seq = Sequence::new();
        let mut a = int_step(1, "f");
        a.set_call_range(1.into());
        seq.append_expectation(a);
        let mut b = int_step(2, "f");
        b.set_call_range(1.into());
        seq.append_expectation(b);
        seq.append_expectation(Expectation::new(StrMatcher("x"), "g"));
        seq.append_expectation(int_step(1, "f"));

        record_int(&seq, 1);
        record_int(&seq, 2);

        seq.clear_expectations_for::<StrMatcher>();

        // The remaining int(1) step should still be reached without re-matching the
        // already-fulfilled, exact-once step `a` at index 0.
        record_int(&seq, 1);

        assert!(seq.unfulfilled_steps::<IntMatcher>().is_empty());
    }
}