1 #![cfg(feature = "ron")]
2 
3 use serde_derive::Deserialize;
4 use std::path::PathBuf;
5 
6 use config::{Config, File, FileFormat, Map, Value};
7 use float_cmp::ApproxEqUlps;
8 
9 #[derive(Debug, Deserialize)]
10 struct Place {
11     initials: (char, char),
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::Ron))
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.initials, ('T', 'P'));
49     assert_eq!(s.place.name, "Torre di Pisa");
50     assert!(s.place.longitude.approx_eq_ulps(&43.722_498_5, 2));
51     assert!(s.place.latitude.approx_eq_ulps(&10.397_052_2, 2));
52     assert!(!s.place.favorite);
53     assert_eq!(s.place.reviews, 3866);
54     assert_eq!(s.place.rating, Some(4.5));
55     assert_eq!(s.place.telephone, None);
56     assert_eq!(s.elements.len(), 10);
57     assert_eq!(s.elements[3], "4".to_string());
58     if cfg!(feature = "preserve_order") {
59         assert_eq!(
60             s.place
61                 .creator
62                 .into_iter()
63                 .collect::<Vec<(String, config::Value)>>(),
64             vec![
65                 ("name".to_string(), "John Smith".into()),
66                 ("username".into(), "jsmith".into()),
67                 ("email".into(), "jsmith@localhost".into()),
68             ]
69         );
70     } else {
71         assert_eq!(
72             s.place.creator["name"].clone().into_string().unwrap(),
73             "John Smith".to_string()
74         );
75     }
76 }
77 
78 #[test]
test_error_parse()79 fn test_error_parse() {
80     let mut c = Config::default();
81     let res = c.merge(File::new("tests/Settings-invalid", FileFormat::Ron));
82 
83     let path_with_extension: PathBuf = ["tests", "Settings-invalid.ron"].iter().collect();
84 
85     assert!(res.is_err());
86     assert_eq!(
87         res.unwrap_err().to_string(),
88         format!("4:1: Expected colon in {}", path_with_extension.display())
89     );
90 }
91