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
use std::sync::{
    atomic::{AtomicUsize, Ordering},
    Arc,
};

type MockFn<RETURN, ARGS> = dyn Fn(ARGS) -> RETURN + Send + Sync;

/// Struct that represents a function mock.
///
/// **This is supported on `feature=mock` only.**
///
/// [Example](https://github.com/leroyguillaume/mockable/tree/main/examples/mock.rs).
pub struct Mock<RETURN, ARGS = ()> {
    idx: Arc<AtomicUsize>,
    kind: MockKind<RETURN, ARGS>,
}

impl<RETURN, ARGS> Mock<RETURN, ARGS> {
    /// Creates a new `Mock` that always returns always the same result.
    pub fn always_with_args<F: Fn(usize, ARGS) -> RETURN + Send + Sync + 'static>(f: F) -> Self {
        Self {
            idx: Arc::new(AtomicUsize::new(0)),
            kind: MockKind::Always(Arc::new(Box::new(f))),
        }
    }

    /// Creates a new `Mock` that should never be called.
    pub fn never() -> Self {
        Self::with(vec![])
    }

    /// Creates a new `Mock` that should be called only once.
    pub fn once_with_args<F: Fn(ARGS) -> RETURN + Send + Sync + 'static>(f: F) -> Self {
        Self::with(vec![Box::new(f)])
    }

    /// Creates a new `Mock` that should be called several times.
    pub fn with(f: Vec<Box<dyn Fn(ARGS) -> RETURN + Send + Sync>>) -> Self {
        Self {
            idx: Arc::new(AtomicUsize::new(0)),
            kind: MockKind::CallSpecific(Arc::new(f)),
        }
    }

    /// Returns the result of the mock.
    ///
    /// # Panics
    /// Panics if the mock has been called more times than expected.
    pub fn call_with_args(&self, args: ARGS) -> RETURN {
        let idx = self.idx.fetch_add(1, Ordering::Relaxed);
        match &self.kind {
            MockKind::Always(f) => f(idx, args),
            MockKind::CallSpecific(fns) => {
                if idx >= fns.len() {
                    panic!("Mock called when it should not have been");
                }
                fns[idx](args)
            }
        }
    }

    /// Returns the number of times the mock has been called.
    pub fn count(&self) -> usize {
        self.idx.load(Ordering::Relaxed)
    }

    /// Returns the number of times the mock is expected to be called.
    ///
    /// If the mock is expected to return always the same value, `usize::MAX` is returned.
    pub fn times(&self) -> usize {
        match &self.kind {
            MockKind::Always(_) => usize::MAX,
            MockKind::CallSpecific(fns) => fns.len(),
        }
    }
}

impl<RETURN> Mock<RETURN, ()> {
    /// Creates a new `Mock` that always returns always the same result.
    pub fn always<F: Fn(usize) -> RETURN + Send + Sync + 'static>(f: F) -> Self {
        Self::always_with_args(move |idx, _| f(idx))
    }

    /// Creates a new `Mock` that should be called only once.
    pub fn once<F: Fn() -> RETURN + Send + Sync + 'static>(f: F) -> Self {
        Self::once_with_args(move |_| f())
    }

    /// Returns the result of the mock.
    ///
    /// # Panics
    /// Panics if the mock has been called more times than expected.
    pub fn call(&self) -> RETURN {
        self.call_with_args(())
    }
}

impl<RETURN, ARGS> Clone for Mock<RETURN, ARGS> {
    fn clone(&self) -> Self {
        Self {
            idx: self.idx.clone(),
            kind: self.kind.clone(),
        }
    }
}

impl<RETURN, ARGS> Default for Mock<RETURN, ARGS> {
    fn default() -> Self {
        Self::never()
    }
}

// MockKind

enum MockKind<RETURN, ARGS> {
    Always(Arc<Box<dyn Fn(usize, ARGS) -> RETURN + Send + Sync>>),
    CallSpecific(Arc<Vec<Box<MockFn<RETURN, ARGS>>>>),
}

impl<RETURN, ARGS> Clone for MockKind<RETURN, ARGS> {
    fn clone(&self) -> Self {
        match self {
            MockKind::Always(f) => MockKind::Always(f.clone()),
            MockKind::CallSpecific(fns) => MockKind::CallSpecific(fns.clone()),
        }
    }
}