|
| 1 | +use async_trait::async_trait; |
| 2 | +use std::{collections::VecDeque, sync::Mutex}; |
| 3 | + |
| 4 | +use crate::{entities::ChainPoint, StdResult}; |
| 5 | + |
| 6 | +use super::{ChainBlockNextAction, ChainBlockReader}; |
| 7 | + |
| 8 | +/// [FakeChainReader] is a fake implementation of [ChainBlockReader] for testing purposes. |
| 9 | +pub struct FakeChainReader { |
| 10 | + chain_point_next_actions: Mutex<VecDeque<ChainBlockNextAction>>, |
| 11 | +} |
| 12 | + |
| 13 | +impl FakeChainReader { |
| 14 | + /// Creates a new [FakeChainReader] instance. |
| 15 | + pub fn new(chain_point_next_actions: Vec<ChainBlockNextAction>) -> Self { |
| 16 | + Self { |
| 17 | + chain_point_next_actions: Mutex::new(chain_point_next_actions.into()), |
| 18 | + } |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +#[async_trait] |
| 23 | +impl ChainBlockReader for FakeChainReader { |
| 24 | + async fn set_chain_point(&mut self, _point: &ChainPoint) -> StdResult<()> { |
| 25 | + Ok(()) |
| 26 | + } |
| 27 | + |
| 28 | + async fn get_next_chain_block(&mut self) -> StdResult<Option<ChainBlockNextAction>> { |
| 29 | + Ok(self.chain_point_next_actions.lock().unwrap().pop_front()) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +#[cfg(test)] |
| 34 | +mod tests { |
| 35 | + use crate::cardano_block_scanner::ScannedBlock; |
| 36 | + |
| 37 | + use super::*; |
| 38 | + |
| 39 | + fn build_chain_point(id: u64) -> ChainPoint { |
| 40 | + ChainPoint { |
| 41 | + slot_number: id, |
| 42 | + block_number: id, |
| 43 | + block_hash: format!("point-hash-{id}"), |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + #[tokio::test] |
| 48 | + async fn test_get_next_chain_block() { |
| 49 | + let expected_chain_point_next_actions = vec![ |
| 50 | + ChainBlockNextAction::RollForward { |
| 51 | + next_point: build_chain_point(1), |
| 52 | + parsed_block: ScannedBlock::new("hash-1", 1, 10, 20, Vec::<&str>::new()), |
| 53 | + }, |
| 54 | + ChainBlockNextAction::RollForward { |
| 55 | + next_point: build_chain_point(2), |
| 56 | + parsed_block: ScannedBlock::new("hash-2", 2, 11, 21, Vec::<&str>::new()), |
| 57 | + }, |
| 58 | + ChainBlockNextAction::RollBackward { |
| 59 | + rollback_point: build_chain_point(1), |
| 60 | + }, |
| 61 | + ]; |
| 62 | + |
| 63 | + let mut chain_reader = FakeChainReader::new(expected_chain_point_next_actions.clone()); |
| 64 | + |
| 65 | + let mut chain_point_next_actions = vec![]; |
| 66 | + while let Some(chain_block_next_action) = chain_reader.get_next_chain_block().await.unwrap() |
| 67 | + { |
| 68 | + chain_point_next_actions.push(chain_block_next_action); |
| 69 | + } |
| 70 | + |
| 71 | + assert_eq!(expected_chain_point_next_actions, chain_point_next_actions); |
| 72 | + } |
| 73 | +} |
0 commit comments