1 #![cfg(feature = "yaml")]
2
3 use serde_derive::Deserialize;
4
5 use std::path::PathBuf;
6
7 use config::{Config, File, FileFormat, Map, Value};
8 use float_cmp::ApproxEqUlps;
9
10 #[derive(Debug, Deserialize)]
11 struct Place {
12 name: String,
13 longitude: f64,
14 latitude: f64,
15 favorite: bool,
16 telephone: Option<String>,
17 reviews: u64,
18 creator: Map<String, Value>,
19 rating: Option<f32>,
20 }
21
22 #[derive(Debug, Deserialize)]
23 struct Settings {
24 debug: f64,
25 production: Option<String>,
26 place: Place,
27 #[serde(rename = "arr")]
28 elements: Vec<String>,
29 }
30
make() -> Config31 fn make() -> Config {
32 let mut c = Config::default();
33 c.merge(File::new("tests/Settings", FileFormat::Yaml))
34 .unwrap();
35
36 c
37 }
38
39 #[test]
test_file()40 fn test_file() {
41 let c = make();
42
43 // Deserialize the entire file as single struct
44 let s: Settings = c.try_deserialize().unwrap();
45
46 assert!(s.debug.approx_eq_ulps(&1.0, 2));
47 assert_eq!(s.production, Some("false".to_string()));
48 assert_eq!(s.place.name, "Torre di Pisa");
49 assert!(s.place.longitude.approx_eq_ulps(&43.722_498_5, 2));
50 assert!(s.place.latitude.approx_eq_ulps(&10.397_052_2, 2));
51 assert!(!s.place.favorite);
52 assert_eq!(s.place.reviews, 3866);
53 assert_eq!(s.place.rating, Some(4.5));
54 assert_eq!(s.place.telephone, None);
55 assert_eq!(s.elements.len(), 10);
56 assert_eq!(s.elements[3], "4".to_string());
57 if cfg!(feature = "preserve_order") {
58 assert_eq!(
59 s.place
60 .creator
61 .into_iter()
62 .collect::<Vec<(String, config::Value)>>(),
63 vec![
64 ("name".to_string(), "John Smith".into()),
65 ("username".into(), "jsmith".into()),
66 ("email".into(), "jsmith@localhost".into()),
67 ]
68 );
69 } else {
70 assert_eq!(
71 s.place.creator["name"].clone().into_string().unwrap(),
72 "John Smith".to_string()
73 );
74 }
75 }
76
77 #[test]
test_error_parse()78 fn test_error_parse() {
79 let mut c = Config::default();
80 let res = c.merge(File::new("tests/Settings-invalid", FileFormat::Yaml));
81
82 let path_with_extension: PathBuf = ["tests", "Settings-invalid.yaml"].iter().collect();
83
84 assert!(res.is_err());
85 assert_eq!(
86 res.unwrap_err().to_string(),
87 format!(
88 "while parsing a block mapping, did not find expected key at \
89 line 2 column 1 in {}",
90 path_with_extension.display()
91 )
92 );
93 }
94