1 #![cfg(feature = "ron")]
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     initials: (char, char),
13     name: String,
14     longitude: f64,
15     latitude: f64,
16     favorite: bool,
17     telephone: Option<String>,
18     reviews: u64,
19     creator: Map<String, Value>,
20     rating: Option<f32>,
21 }
22 
23 #[derive(Debug, Deserialize)]
24 struct Settings {
25     debug: f64,
26     production: Option<String>,
27     place: Place,
28     #[serde(rename = "arr")]
29     elements: Vec<String>,
30 }
31 
make() -> Config32 fn make() -> Config {
33     Config::builder()
34         .add_source(File::new("tests/Settings", FileFormat::Ron))
35         .build()
36         .unwrap()
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 res = Config::builder()
81         .add_source(File::new("tests/Settings-invalid", FileFormat::Ron))
82         .build();
83 
84     let path_with_extension: PathBuf = ["tests", "Settings-invalid.ron"].iter().collect();
85 
86     assert!(res.is_err());
87     assert_eq!(
88         res.unwrap_err().to_string(),
89         format!("4:1: Expected colon in {}", path_with_extension.display())
90     );
91 }
92