libhoney/
mock.rs

1/*!
2Mock module to ease testing
3    */
4use crossbeam_channel::{bounded, Receiver};
5
6use crate::response::Response;
7use crate::sender::Sender;
8use crate::transmission::Options;
9use crate::Event;
10use crate::Result;
11
12/// Transmission mocker for use in tests (mostly in beeline-rust)
13#[derive(Debug, Clone)]
14pub struct TransmissionMock {
15    started: usize,
16    stopped: usize,
17    events_called: usize,
18    events: Vec<Event>,
19    responses: Receiver<Response>,
20    block_on_responses: bool,
21}
22
23impl Sender for TransmissionMock {
24    // `send` queues up an event to be sent
25    fn send(&mut self, ev: Event) {
26        self.events.push(ev);
27    }
28
29    // `start` initializes any background processes necessary to send events
30    fn start(&mut self) {
31        self.started += 1;
32    }
33
34    // `stop` flushes any pending queues and blocks until everything in flight has
35    // been sent
36    fn stop(&mut self) -> Result<()> {
37        self.stopped += 1;
38        Ok(())
39    }
40
41    // `responses` returns a channel that will contain a single Response for each
42    // Event added. Note that they may not be in the same order as they came in
43    fn responses(&self) -> Receiver<Response> {
44        self.responses.clone()
45    }
46}
47
48impl TransmissionMock {
49    pub(crate) fn new(options: Options) -> Result<Self> {
50        let (_, responses) = bounded(options.pending_work_capacity * 4);
51
52        Ok(Self {
53            started: 0,
54            stopped: 0,
55            events_called: 0,
56            events: Vec::new(),
57            block_on_responses: false,
58            responses,
59        })
60    }
61
62    /// events
63    pub fn events(&mut self) -> Vec<Event> {
64        self.events_called += 1;
65        self.events.clone()
66    }
67}