Skip to main content

objectstore_inventory_tracker/
test_utils.rs

1//! Helpers for asserting on emitted records without a broker.
2
3use std::sync::{Arc, Mutex};
4use std::time::Duration;
5
6use crate::{InventoryRecord, Producer};
7
8/// A [`Producer`] that records everything it is given, for assertions in tests.
9///
10/// Cloning shares the same buffer, so a clone can be handed to an
11/// [`InventoryTracker`](crate::InventoryTracker) while the original is used to read
12/// back what was emitted.
13#[derive(Clone, Debug, Default)]
14pub struct DummyProducer {
15    sent: Arc<Mutex<Vec<SentMessage>>>,
16}
17
18/// A message as handed to [`Producer::send`], as `(key, payload)`.
19pub type SentMessage = (Vec<u8>, Vec<u8>);
20
21impl DummyProducer {
22    /// Returns the raw messages sent so far, in order.
23    pub fn raw(&self) -> Vec<SentMessage> {
24        self.sent.lock().unwrap().clone()
25    }
26
27    /// Returns the records sent so far, deserialized, in order.
28    pub fn records(&self) -> Vec<InventoryRecord> {
29        self.raw()
30            .iter()
31            .map(|(_, payload)| serde_json::from_slice(payload).unwrap())
32            .collect()
33    }
34
35    /// Discards everything sent so far.
36    pub fn clear(&self) {
37        self.sent.lock().unwrap().clear();
38    }
39}
40
41impl Producer for DummyProducer {
42    type Error = std::convert::Infallible;
43
44    fn send(&self, key: &[u8], payload: Vec<u8>) -> Result<(), Self::Error> {
45        self.sent.lock().unwrap().push((key.to_vec(), payload));
46        Ok(())
47    }
48
49    // Nothing is ever queued, so there is nothing to wait for.
50    fn join_blocking(&self, _timeout: Duration) -> Result<(), Self::Error> {
51        Ok(())
52    }
53}