muse2/input/
region.rs

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