muse2/input/
region.rs

1//! Code for reading region-related information from CSV files.
2use super::*;
3use crate::region::RegionMap;
4use std::path::Path;
5
6const REGIONS_FILE_NAME: &str = "regions.csv";
7
8/// Reads regions from a CSV file.
9///
10/// # Arguments
11///
12/// * `model_dir` - Folder containing model configuration files
13///
14/// # Returns
15///
16/// A `HashMap<RegionID, Region>` with the parsed regions data or an error
17pub fn read_regions(model_dir: &Path) -> Result<RegionMap> {
18    read_csv_id_file(&model_dir.join(REGIONS_FILE_NAME))
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24    use crate::region::Region;
25    use std::fs::File;
26    use std::io::Write;
27    use std::path::Path;
28    use tempfile::tempdir;
29
30    /// Create an example regions file in dir_path
31    fn create_regions_file(dir_path: &Path) {
32        let file_path = dir_path.join(REGIONS_FILE_NAME);
33        let mut file = File::create(file_path).unwrap();
34        writeln!(
35            file,
36            "id,description
37NA,North America
38EU,Europe
39AP,Asia Pacific"
40        )
41        .unwrap();
42    }
43
44    #[test]
45    fn test_read_regions() {
46        let dir = tempdir().unwrap();
47        create_regions_file(dir.path());
48        let regions = read_regions(dir.path()).unwrap();
49        assert_eq!(
50            regions,
51            RegionMap::from([
52                (
53                    "NA".into(),
54                    Region {
55                        id: "NA".into(),
56                        description: "North America".to_string(),
57                    }
58                ),
59                (
60                    "EU".into(),
61                    Region {
62                        id: "EU".into(),
63                        description: "Europe".to_string(),
64                    }
65                ),
66                (
67                    "AP".into(),
68                    Region {
69                        id: "AP".into(),
70                        description: "Asia Pacific".to_string(),
71                    }
72                ),
73            ])
74        )
75    }
76}