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      Config::builder()
33          .add_source(File::new("tests/Settings", FileFormat::Yaml))
34          .build()
35          .unwrap()
36  }
37  
38  #[test]
test_file()39  fn test_file() {
40      let c = make();
41  
42      // Deserialize the entire file as single struct
43      let s: Settings = c.try_deserialize().unwrap();
44  
45      assert!(s.debug.approx_eq_ulps(&1.0, 2));
46      assert_eq!(s.production, Some("false".to_string()));
47      assert_eq!(s.place.name, "Torre di Pisa");
48      assert!(s.place.longitude.approx_eq_ulps(&43.722_498_5, 2));
49      assert!(s.place.latitude.approx_eq_ulps(&10.397_052_2, 2));
50      assert!(!s.place.favorite);
51      assert_eq!(s.place.reviews, 3866);
52      assert_eq!(s.place.rating, Some(4.5));
53      assert_eq!(s.place.telephone, None);
54      assert_eq!(s.elements.len(), 10);
55      assert_eq!(s.elements[3], "4".to_string());
56      if cfg!(feature = "preserve_order") {
57          assert_eq!(
58              s.place
59                  .creator
60                  .into_iter()
61                  .collect::<Vec<(String, config::Value)>>(),
62              vec![
63                  ("name".to_string(), "John Smith".into()),
64                  ("username".into(), "jsmith".into()),
65                  ("email".into(), "jsmith@localhost".into()),
66              ]
67          );
68      } else {
69          assert_eq!(
70              s.place.creator["name"].clone().into_string().unwrap(),
71              "John Smith".to_string()
72          );
73      }
74  }
75  
76  #[test]
test_error_parse()77  fn test_error_parse() {
78      let res = Config::builder()
79          .add_source(File::new("tests/Settings-invalid", FileFormat::Yaml))
80          .build();
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