use serde_json;
use std::fs::File;
use std::io::prelude::*;
use yaml_rust::YamlLoader;
#[derive(Serialize, Deserialize, Debug)]
pub struct Configs {
file: String,
}
impl Configs {
pub fn new(path: &String) -> Configs {
let pth = path.to_string().to_owned();
Configs { file: pth }
}
pub fn from_serialized(serialized: &str) -> Configs {
serde_json::from_str(&serialized).unwrap()
}
pub fn get_config_file_path(&self) -> &str {
&self.file
}
pub fn load_config_file(&mut self) {
let mut f = File::open(&self.file).expect(&format!(
"Error: Configuration file not found at {}",
&self.file.to_string()
));
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect("Something went wrong reading file");
let _cfg_yaml =
&YamlLoader::load_from_str(&*contents).expect("failed to load YAML file")[0];
}
pub fn serialize(&mut self) -> String {
serde_json::to_string(&self).unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_config_good_cfg_file() {
let mut cfg = Configs::new(&String::from("./tests/config/tdg.yaml"));
cfg.load_config_file();
}
#[test]
#[should_panic(expected = "Error: Configuration file not found at ./badpath/tdg.yaml")]
fn create_config_bad_cfg_file() {
let mut cfg = Configs::new(&String::from("./badpath/tdg.yaml"));
cfg.load_config_file();
}
#[test]
fn new_fact_from_serialized() {
let serialized = "{\"file\":\"./tests/config/tdg.yaml\"}";
let cfg = Configs::from_serialized(&serialized);
assert_eq!(cfg.get_config_file_path(), "./tests/config/tdg.yaml");
}
#[test]
fn serialize() {
let mut cfg = Configs::new(&String::from("./tests/config/tdg.yaml"));
cfg.load_config_file();
let serialized = cfg.serialize();
println!("serialized : {}", serialized);
assert_eq!(serialized, "{\"file\":\"./tests/config/tdg.yaml\"}");
}
}