embedded-hal-mock 0.11.1

A collection of mocked devices that implement the embedded-hal traits
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
//! Mock digital [`InputPin`], [`OutputPin`], and [`ToggleableOutputPin`] v2 implementations
//!
//! [`InputPin`]: https://docs.rs/embedded-hal/0.2/embedded_hal/digital/v2/trait.InputPin.html
//! [`OutputPin`]: https://docs.rs/embedded-hal/0.2/embedded_hal/digital/v2/trait.OutputPin.html
//! [`ToggleableOutputPin`]: https://docs.rs/embedded-hal/0.2/embedded_hal/digital/v2/trait.ToggleableOutputPin.html
//!
//! ```
//! # use eh0 as embedded_hal;
//! use std::io::ErrorKind;
//!
//! use embedded_hal::digital::v2::{InputPin, OutputPin, ToggleableOutputPin};
//! use embedded_hal_mock::eh0::{
//!     digital::{Mock as PinMock, State as PinState, Transaction as PinTransaction},
//!     MockError,
//! };
//!
//! let err = MockError::Io(ErrorKind::NotConnected);
//!
//! // Configure expectations
//! let expectations = [
//!     PinTransaction::get(PinState::High),
//!     PinTransaction::get(PinState::High),
//!     PinTransaction::set(PinState::Low),
//!     PinTransaction::set(PinState::High).with_error(err.clone()),
//!     PinTransaction::toggle(),
//! ];
//!
//! // Create pin
//! let mut pin = PinMock::new(&expectations);
//!
//! // Run and test
//! assert_eq!(pin.is_high().unwrap(), true);
//! assert_eq!(pin.is_low().unwrap(), false);
//!
//! pin.set_low().unwrap();
//! pin.set_high().expect_err("expected error return");
//!
//! pin.toggle().unwrap();
//!
//! pin.done();
//!
//! // Update expectations
//! pin.update_expectations(&[]);
//! // ...
//! pin.done();
//! ```

use eh0 as embedded_hal;
use embedded_hal::{
    digital::v2::{InputPin, OutputPin, ToggleableOutputPin},
    PwmPin,
};

use super::error::MockError;
use crate::common::Generic;

/// The type used for the duty of the [`PwmPin`] mock.
pub type PwmDuty = u16;

/// MockPin transaction
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Transaction {
    /// Kind is the transaction kind (and data) expected
    kind: TransactionKind,
    /// An optional error return value for a transaction. This is in addition
    /// to `kind` to allow validation that the transaction kind is correct
    /// prior to returning the error.
    err: Option<MockError>,
}

#[derive(PartialEq, Eq, Copy, Clone, Debug)]
/// Digital pin value enumeration
pub enum State {
    /// Digital low state
    Low,
    /// Digital high state
    High,
}

impl Transaction {
    /// Create a new pin transaction
    pub fn new(kind: TransactionKind) -> Transaction {
        Transaction { kind, err: None }
    }

    /// Create a new get transaction
    pub fn get(state: State) -> Transaction {
        Transaction::new(TransactionKind::Get(state))
    }

    /// Create a new toggle transaction
    pub fn toggle() -> Transaction {
        Transaction::new(TransactionKind::Toggle)
    }

    /// Create a new get transaction
    pub fn set(state: State) -> Transaction {
        Transaction::new(TransactionKind::Set(state))
    }

    /// Create a new disable transaction
    pub fn disable() -> Transaction {
        Transaction::new(TransactionKind::Disable)
    }

    /// Create a new enable transaction
    pub fn enable() -> Transaction {
        Transaction::new(TransactionKind::Enable)
    }

    /// Create a new get_duty transaction
    pub fn get_duty(duty: PwmDuty) -> Transaction {
        Transaction::new(TransactionKind::GetDuty(duty))
    }

    /// Create a new get_max_duty transaction
    pub fn get_max_duty(max_duty: PwmDuty) -> Transaction {
        Transaction::new(TransactionKind::GetMaxDuty(max_duty))
    }

    /// Create a new set_duty transaction
    pub fn set_duty(expected_duty: PwmDuty) -> Transaction {
        Transaction::new(TransactionKind::SetDuty(expected_duty))
    }

    /// Add an error return to a transaction
    ///
    /// This is used to mock failure behaviours.
    ///
    /// Note that this can only be used for methods which actually return a [`Result`];
    /// trying to invoke this for others will lead to an assertion error!
    pub fn with_error(mut self, error: MockError) -> Self {
        assert!(
            self.kind.supports_errors(),
            "the transaction kind supports errors"
        );
        self.err = Some(error);
        self
    }
}

/// MockPin transaction kind.
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum TransactionKind {
    /// Set the pin state
    Set(State),
    /// Get the pin state
    Get(State),
    /// Toggle the pin state
    Toggle,
    /// Disable a [`PwmPin`] using [`PwmPin::disable`]
    Disable,
    /// Enable a [`PwmPin`] using [`PwmPin::enable`]
    Enable,
    /// Query the duty of a [`PwmPin`] using [`PwmPin::get_duty`], returning the specified value
    GetDuty(PwmDuty),
    /// Query the max. duty of a [`PwmPin`] using [`PwmPin::get_max_duty`], returning the specified value
    GetMaxDuty(PwmDuty),
    /// Set the duty of a [`PwmPin`] using [`PwmPin::set_duty`], expecting the specified value
    SetDuty(PwmDuty),
}

impl TransactionKind {
    fn is_get(&self) -> bool {
        match self {
            TransactionKind::Get(_) => true,
            _ => false,
        }
    }

    /// Specifies whether the actual API returns a [`Result`] (= supports errors) or not.
    fn supports_errors(&self) -> bool {
        match self {
            TransactionKind::Set(_) | TransactionKind::Get(_) | TransactionKind::Toggle => true,
            _ => false,
        }
    }
}

/// Mock Pin implementation
pub type Mock = Generic<Transaction>;

/// Single digital push-pull output pin
impl OutputPin for Mock {
    /// Error type
    type Error = MockError;

    /// Drives the pin low
    fn set_low(&mut self) -> Result<(), Self::Error> {
        let Transaction { kind, err } = self.next().expect("no expectation for pin::set_low call");

        assert_eq!(
            kind,
            TransactionKind::Set(State::Low),
            "expected pin::set_low"
        );

        match err {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }

    /// Drives the pin high
    fn set_high(&mut self) -> Result<(), Self::Error> {
        let Transaction { kind, err } = self.next().expect("no expectation for pin::set_high call");

        assert_eq!(
            kind,
            TransactionKind::Set(State::High),
            "expected pin::set_high"
        );

        match err {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }
}

impl InputPin for Mock {
    /// Error type
    type Error = MockError;

    /// Is the input pin high?
    fn is_high(&self) -> Result<bool, Self::Error> {
        let mut s = self.clone();

        let Transaction { kind, err } = s.next().expect("no expectation for pin::is_high call");

        assert!(kind.is_get(), "expected pin::get");

        if let Some(e) = err {
            Err(e)
        } else if let TransactionKind::Get(v) = kind {
            Ok(v == State::High)
        } else {
            unreachable!();
        }
    }

    /// Is the input pin low?
    fn is_low(&self) -> Result<bool, Self::Error> {
        let mut s = self.clone();

        let Transaction { kind, err } = s.next().expect("no expectation for pin::is_low call");

        assert!(kind.is_get(), "expected pin::get");

        if let Some(e) = err {
            Err(e)
        } else if let TransactionKind::Get(v) = kind {
            Ok(v == State::Low)
        } else {
            unreachable!();
        }
    }
}

/// Single digital output pin that can be toggled between high and low states
impl ToggleableOutputPin for Mock {
    /// Error type
    type Error = MockError;

    /// Toggle the pin low to high or high to low
    fn toggle(&mut self) -> Result<(), Self::Error> {
        let Transaction { kind, err } = self.next().expect("no expectation for pin::toggle call");

        assert_eq!(kind, TransactionKind::Toggle, "expected pin::toggle");

        match err {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }
}

impl PwmPin for Mock {
    type Duty = PwmDuty;

    fn disable(&mut self) {
        // Note: Error is being ignored, because method doesn't return a result
        let Transaction { kind, .. } = self.next().expect("no expectation for pin::disable call");

        assert_eq!(kind, TransactionKind::Disable, "expected pin::disable");
    }

    fn enable(&mut self) {
        // Note: Error is being ignored, because method doesn't return a result
        let Transaction { kind, .. } = self.next().expect("no expectation for pin::enable call");

        assert_eq!(kind, TransactionKind::Enable, "expected pin::enable");
    }

    fn get_duty(&self) -> Self::Duty {
        let mut s = self.clone();

        // Note: Error is being ignored, because method doesn't return a result
        let Transaction { kind, .. } = s.next().expect("no expectation for pin::get_duty call");

        if let TransactionKind::GetDuty(duty) = kind {
            duty
        } else {
            panic!("expected pin::get_duty");
        }
    }

    fn get_max_duty(&self) -> Self::Duty {
        let mut s = self.clone();

        // Note: Error is being ignored, because method doesn't return a result
        let Transaction { kind, .. } = s.next().expect("no expectation for pin::get_max_duty call");

        if let TransactionKind::GetMaxDuty(max_duty) = kind {
            max_duty
        } else {
            panic!("expected pin::get_max_duty");
        }
    }

    fn set_duty(&mut self, duty: Self::Duty) {
        // Note: Error is being ignored, because method doesn't return a result
        let Transaction { kind, .. } = self.next().expect("no expectation for pin::set_duty call");

        assert_eq!(
            kind,
            TransactionKind::SetDuty(duty),
            "expected pin::set_duty"
        );
    }
}

#[cfg(test)]
mod test {
    use std::io::ErrorKind;

    use eh0 as embedded_hal;
    use embedded_hal::{
        digital::v2::{InputPin, OutputPin},
        PwmPin,
    };

    use super::{super::error::MockError, TransactionKind::*, *};

    #[test]
    fn test_input_pin() {
        let expectations = [
            Transaction::new(Get(State::High)),
            Transaction::new(Get(State::High)),
            Transaction::new(Get(State::Low)),
            Transaction::new(Get(State::Low)),
            Transaction::new(Get(State::High)).with_error(MockError::Io(ErrorKind::NotConnected)),
        ];
        let mut pin = Mock::new(&expectations);

        assert_eq!(pin.is_high().unwrap(), true);
        assert_eq!(pin.is_low().unwrap(), false);
        assert_eq!(pin.is_high().unwrap(), false);
        assert_eq!(pin.is_low().unwrap(), true);

        pin.is_low().expect_err("expected error return");

        pin.done();
    }

    #[test]
    fn test_output_pin() {
        let expectations = [
            Transaction::new(Set(State::High)),
            Transaction::new(Set(State::Low)),
            Transaction::new(Set(State::High)).with_error(MockError::Io(ErrorKind::NotConnected)),
        ];
        let mut pin = Mock::new(&expectations);

        pin.set_high().unwrap();
        pin.set_low().unwrap();

        pin.set_high().expect_err("expected error return");

        pin.done();
    }

    #[test]
    fn test_toggleable_output_pin() {
        let expectations = [
            Transaction::new(Toggle),
            Transaction::toggle(),
            Transaction::new(Toggle).with_error(MockError::Io(ErrorKind::NotConnected)),
        ];
        let mut pin = Mock::new(&expectations);

        pin.toggle().unwrap();
        pin.toggle().unwrap();

        pin.toggle().expect_err("expected error return");

        pin.done();
    }

    #[test]
    fn test_pwm_pin() {
        let expected_duty = 10_000;
        let expectations = [
            Transaction::new(Enable),
            Transaction::new(GetMaxDuty(expected_duty)),
            Transaction::new(SetDuty(expected_duty)),
            Transaction::new(GetDuty(expected_duty)),
            Transaction::new(Disable),
        ];
        let mut pin = Mock::new(&expectations);

        pin.enable();
        let max_duty = pin.get_max_duty();
        pin.set_duty(max_duty);
        assert_eq!(pin.get_duty(), expected_duty);
        pin.disable();

        pin.done();
    }
}