1 #![cfg(feature = "toml")]
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 number: PlaceNumber,
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, PartialEq)]
23 struct PlaceNumber(u8);
24
25 #[derive(Debug, Deserialize, PartialEq)]
26 struct AsciiCode(i8);
27
28 #[derive(Debug, Deserialize)]
29 struct Settings {
30 debug: f64,
31 production: Option<String>,
32 code: AsciiCode,
33 place: Place,
34 #[serde(rename = "arr")]
35 elements: Vec<String>,
36 }
37
38 #[cfg(test)]
make() -> Config39 fn make() -> Config {
40 let mut c = Config::default();
41 c.merge(File::new("tests/Settings", FileFormat::Toml))
42 .unwrap();
43
44 c
45 }
46
47 #[test]
test_file()48 fn test_file() {
49 let c = make();
50
51 // Deserialize the entire file as single struct
52 let s: Settings = c.try_deserialize().unwrap();
53
54 assert!(s.debug.approx_eq_ulps(&1.0, 2));
55 assert_eq!(s.production, Some("false".to_string()));
56 assert_eq!(s.code, AsciiCode(53));
57 assert_eq!(s.place.number, PlaceNumber(1));
58 assert_eq!(s.place.name, "Torre di Pisa");
59 assert!(s.place.longitude.approx_eq_ulps(&43.722_498_5, 2));
60 assert!(s.place.latitude.approx_eq_ulps(&10.397_052_2, 2));
61 assert!(!s.place.favorite);
62 assert_eq!(s.place.reviews, 3866);
63 assert_eq!(s.place.rating, Some(4.5));
64 assert_eq!(s.place.telephone, None);
65 assert_eq!(s.elements.len(), 10);
66 assert_eq!(s.elements[3], "4".to_string());
67 if cfg!(feature = "preserve_order") {
68 assert_eq!(
69 s.place
70 .creator
71 .into_iter()
72 .collect::<Vec<(String, config::Value)>>(),
73 vec![
74 ("name".to_string(), "John Smith".into()),
75 ("username".into(), "jsmith".into()),
76 ("email".into(), "jsmith@localhost".into()),
77 ]
78 );
79 } else {
80 assert_eq!(
81 s.place.creator["name"].clone().into_string().unwrap(),
82 "John Smith".to_string()
83 );
84 }
85 }
86
87 #[test]
test_error_parse()88 fn test_error_parse() {
89 let mut c = Config::default();
90 let res = c.merge(File::new("tests/Settings-invalid", FileFormat::Toml));
91
92 let path_with_extension: PathBuf = ["tests", "Settings-invalid.toml"].iter().collect();
93
94 assert!(res.is_err());
95 assert_eq!(
96 res.unwrap_err().to_string(),
97 format!(
98 "invalid TOML value, did you mean to use a quoted string? at line 2 column 9 in {}",
99 path_with_extension.display()
100 )
101 );
102 }
103