summaryrefslogtreecommitdiffstats
path: root/third_party/rust/fluent-testing/src/fs.rs
blob: 1efd6a90cbe37ec8954a89a33bb592d66edc7670 (plain)
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
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;

#[derive(Default)]
pub struct MockFileSystem {
    files: RefCell<HashMap<String, std::io::Result<String>>>,
}

impl MockFileSystem {
    pub fn clear(&self) {
        self.files.borrow_mut().clear();
    }

    fn get_test_file_path() -> PathBuf {
        PathBuf::from(std::env!("CARGO_MANIFEST_DIR")).join("resources")
    }

    fn get_file(&self, path: &str) -> std::io::Result<String> {
        let mut tmp = self.files.borrow_mut();
        let result = tmp.entry(path.to_string()).or_insert_with(|| {
            let root_path = Self::get_test_file_path();
            let full_path = root_path.join(path);
            std::fs::read_to_string(full_path)
        });
        match result {
            Ok(s) => Ok(s.to_string()),
            Err(e) => Err(std::io::Error::new(e.kind(), "Error")),
        }
    }

    #[cfg(feature = "sync")]
    pub fn get_test_file_sync(&self, path: &str) -> std::io::Result<String> {
        self.get_file(path)
    }

    #[cfg(feature = "async")]
    pub async fn get_test_file_async(&self, path: &str) -> std::io::Result<String> {
        self.get_file(path)
    }
}