mithril_cardano_node_chain/test/double/
chain_reader.rs

1use std::{collections::VecDeque, sync::Mutex};
2
3use async_trait::async_trait;
4
5use mithril_common::StdResult;
6
7use crate::entities::{ChainBlockNextAction, RawCardanoPoint};
8
9use crate::chain_reader::ChainBlockReader;
10
11/// [FakeChainReader] is a fake implementation of [ChainBlockReader] for testing purposes.
12pub struct FakeChainReader {
13    chain_block_next_actions: Mutex<VecDeque<ChainBlockNextAction>>,
14}
15
16impl FakeChainReader {
17    /// Creates a new [FakeChainReader] instance.
18    pub fn new(chain_block_next_actions: Vec<ChainBlockNextAction>) -> Self {
19        Self {
20            chain_block_next_actions: Mutex::new(chain_block_next_actions.into()),
21        }
22    }
23
24    /// Total remaining next actions
25    pub fn get_total_remaining_next_actions(&self) -> usize {
26        self.chain_block_next_actions.lock().unwrap().len()
27    }
28}
29
30#[async_trait]
31impl ChainBlockReader for FakeChainReader {
32    async fn set_chain_point(&mut self, _point: &RawCardanoPoint) -> StdResult<()> {
33        Ok(())
34    }
35
36    async fn get_next_chain_block(&mut self) -> StdResult<Option<ChainBlockNextAction>> {
37        Ok(self.chain_block_next_actions.lock().unwrap().pop_front())
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use mithril_common::entities::{BlockNumber, SlotNumber};
44
45    use crate::entities::ScannedBlock;
46
47    use super::*;
48
49    #[tokio::test]
50    async fn test_get_next_chain_block() {
51        let expected_chain_block_next_actions = vec![
52            ChainBlockNextAction::RollForward {
53                parsed_block: ScannedBlock::new(
54                    "hash-1",
55                    BlockNumber(1),
56                    SlotNumber(10),
57                    Vec::<&str>::new(),
58                ),
59            },
60            ChainBlockNextAction::RollForward {
61                parsed_block: ScannedBlock::new(
62                    "hash-2",
63                    BlockNumber(2),
64                    SlotNumber(11),
65                    Vec::<&str>::new(),
66                ),
67            },
68            ChainBlockNextAction::RollBackward {
69                rollback_point: RawCardanoPoint::new(SlotNumber(1), "point-hash-1".as_bytes()),
70            },
71        ];
72
73        let mut chain_reader = FakeChainReader::new(expected_chain_block_next_actions.clone());
74
75        let mut chain_block_next_actions = vec![];
76        while let Some(chain_block_next_action) = chain_reader.get_next_chain_block().await.unwrap()
77        {
78            chain_block_next_actions.push(chain_block_next_action);
79        }
80
81        assert_eq!(expected_chain_block_next_actions, chain_block_next_actions);
82    }
83}