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