mithril_common/era/adapters/
file.rs

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
use async_trait::async_trait;
use std::{fs, path::PathBuf};

use crate::era::{EraMarker, EraReaderAdapter};
use crate::StdResult;

/// File adapter is intended to be used in a test environment
/// to simulate eras transitions.
pub struct FileAdapter {
    markers_file: PathBuf,
}

impl FileAdapter {
    /// File adapter factory
    pub fn new(markers_file: PathBuf) -> Self {
        Self { markers_file }
    }
}

#[async_trait]
impl EraReaderAdapter for FileAdapter {
    async fn read(&self) -> StdResult<Vec<EraMarker>> {
        Ok(serde_json::from_str(&fs::read_to_string(
            &self.markers_file,
        )?)?)
    }
}

#[cfg(test)]
mod tests {
    use crate::entities::Epoch;
    use crate::era::SupportedEra;
    use crate::test_utils::TempDir;

    use super::*;

    fn get_temp_dir(dir_name: &str) -> PathBuf {
        TempDir::create("era-adapter", dir_name)
    }

    #[tokio::test]
    async fn file_adapter_output() {
        let markers = vec![
            EraMarker::new("one", Some(Epoch(1))),
            EraMarker::new(&SupportedEra::dummy().to_string(), None),
            EraMarker::new(&SupportedEra::dummy().to_string(), Some(Epoch(10))),
        ];
        let temp_file = get_temp_dir("era_reader_file_adapter").join("markers.json");
        fs::write(
            &temp_file,
            serde_json::to_string(&markers).expect("serializing markers should not fail"),
        )
        .expect("writing markers to file should not fail");
        let adapter = FileAdapter::new(temp_file);

        assert_eq!(
            markers,
            adapter
                .read()
                .await
                .expect("file adapter shall not fail reading")
        );
    }
}