Skip to content

Commit 8268229

Browse files
committed
fix test cases for jsonc
1 parent ca5784d commit 8268229

File tree

7 files changed

+83
-82
lines changed

7 files changed

+83
-82
lines changed

Cargo.lock

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/file/format/jsonc.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::value::{Value, ValueKind};
66

77
use jsonc_parser::JsonValue;
88

9-
pub fn parse(
9+
pub(crate) fn parse(
1010
uri: Option<&String>,
1111
text: &str,
1212
) -> Result<Map<String, Value>, Box<dyn Error + Send + Sync>> {
@@ -28,7 +28,7 @@ pub fn parse(
2828
.map_err(|err| Box::new(err) as Box<dyn Error + Send + Sync>)
2929
}
3030

31-
fn from_jsonc_value(uri: Option<&String>, value: JsonValue) -> Value {
31+
fn from_jsonc_value(uri: Option<&String>, value: JsonValue<'_>) -> Value {
3232
let vk = match value {
3333
JsonValue::Null => ValueKind::Nil,
3434
JsonValue::String(v) => ValueKind::String(v.to_string()),
File renamed without changes.
File renamed without changes.

tests/file_jsonc.rs renamed to tests/testsuite/file_jsonc.rs

Lines changed: 73 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -4,39 +4,46 @@ use serde_derive::Deserialize;
44

55
use config::{Config, File, FileFormat, Map, Value};
66
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-
30-
fn make() -> Config {
31-
Config::builder()
32-
.add_source(File::new("tests/Settings", FileFormat::Jsonc))
33-
.build()
34-
.unwrap()
7+
use snapbox::{assert_data_eq, str};
8+
9+
fn get_config_file_path(suffix: &str) -> String {
10+
let path = std::path::Path::new(file!());
11+
format!(
12+
"{}/{}/{}{}.jsonc",
13+
env!("CARGO_MANIFEST_DIR"),
14+
path.parent().unwrap().to_str().unwrap(),
15+
path.file_stem().unwrap().to_str().unwrap(),
16+
suffix
17+
)
3518
}
3619

3720
#[test]
3821
fn test_file() {
39-
let c = make();
22+
#[derive(Debug, Deserialize)]
23+
struct Place {
24+
name: String,
25+
longitude: f64,
26+
latitude: f64,
27+
favorite: bool,
28+
telephone: Option<String>,
29+
reviews: u64,
30+
creator: Map<String, Value>,
31+
rating: Option<f32>,
32+
}
33+
34+
#[derive(Debug, Deserialize)]
35+
struct Settings {
36+
debug: f64,
37+
production: Option<String>,
38+
place: Place,
39+
#[serde(rename = "arr")]
40+
elements: Vec<String>,
41+
}
42+
43+
let c = Config::builder()
44+
.add_source(File::new(&get_config_file_path(""), FileFormat::Jsonc))
45+
.build()
46+
.unwrap();
4047

4148
// Deserialize the entire file as single struct
4249
let s: Settings = c.try_deserialize().unwrap();
@@ -52,12 +59,12 @@ fn test_file() {
5259
assert_eq!(s.place.telephone, None);
5360
assert_eq!(s.elements.len(), 10);
5461
assert_eq!(s.elements[3], "4".to_string());
55-
if cfg!(feature = "TODO: preserve_order") {
62+
if cfg!(feature = "preserve_order") {
5663
assert_eq!(
5764
s.place
5865
.creator
5966
.into_iter()
60-
.collect::<Vec<(String, config::Value)>>(),
67+
.collect::<Vec<(String, Value)>>(),
6168
vec![
6269
("name".to_string(), "John Smith".into()),
6370
("username".into(), "jsmith".into()),
@@ -74,69 +81,52 @@ fn test_file() {
7481

7582
#[test]
7683
fn test_error_parse() {
84+
let f = get_config_file_path(".error");
7785
let res = Config::builder()
78-
.add_source(File::new("tests/Settings-invalid", FileFormat::Jsonc))
86+
.add_source(File::new(&f, FileFormat::Jsonc))
7987
.build();
8088

81-
let path_with_extension: PathBuf = ["tests", "Settings-invalid.jsonc"].iter().collect();
82-
8389
assert!(res.is_err());
8490
assert_eq!(
8591
res.unwrap_err().to_string(),
8692
format!(
8793
"Expected a colon after the string or word in an object property on line 4 column 1. in {}",
88-
path_with_extension.display()
94+
std::path::Path::new(&f)
95+
.strip_prefix(std::env::current_dir().unwrap())
96+
.unwrap_or(std::path::Path::new(&f))
97+
.display()
8998
)
9099
);
91100
}
92101

93-
#[derive(Debug, Deserialize, PartialEq)]
94-
enum EnumSettings {
95-
Bar(String),
96-
}
97-
98-
#[derive(Debug, Deserialize, PartialEq)]
99-
struct StructSettings {
100-
foo: String,
101-
bar: String,
102-
}
103102
#[derive(Debug, Deserialize, PartialEq)]
104103
#[allow(non_snake_case)]
105-
struct CapSettings {
104+
struct OverrideSettings {
105+
foo: String,
106106
FOO: String,
107+
bar: String,
107108
}
108109

109110
#[test]
110111
fn test_override_uppercase_value_for_struct() {
111112
std::env::set_var("APP_FOO", "I HAVE BEEN OVERRIDDEN_WITH_UPPER_CASE");
112113

113114
let cfg = Config::builder()
114-
.add_source(File::new("tests/Settings", FileFormat::Jsonc))
115+
.add_source(File::new(&get_config_file_path(""), FileFormat::Jsonc))
115116
.add_source(config::Environment::with_prefix("APP").separator("_"))
116117
.build()
117118
.unwrap();
118119

119-
let cap_settings = cfg.clone().try_deserialize::<CapSettings>();
120-
let lower_settings = cfg.try_deserialize::<StructSettings>().unwrap();
120+
let settings = cfg.try_deserialize::<OverrideSettings>();
121121

122-
match cap_settings {
122+
match settings {
123123
Ok(v) => {
124124
// this assertion will ensure that the map has only lowercase keys
125-
assert_ne!(v.FOO, "FOO should be overridden");
126-
assert_eq!(
127-
lower_settings.foo,
128-
"I HAVE BEEN OVERRIDDEN_WITH_UPPER_CASE".to_string()
129-
);
125+
assert_eq!(v.FOO, "FOO should be overridden");
126+
assert_eq!(v.foo, "I HAVE BEEN OVERRIDDEN_WITH_UPPER_CASE".to_string());
130127
}
131128
Err(e) => {
132-
if e.to_string().contains("missing field `FOO`") {
133-
assert_eq!(
134-
lower_settings.foo,
135-
"I HAVE BEEN OVERRIDDEN_WITH_UPPER_CASE".to_string()
136-
);
137-
} else {
138-
panic!("{}", e);
139-
}
129+
panic!("{}", e);
140130
}
141131
}
142132
}
@@ -146,33 +136,36 @@ fn test_override_lowercase_value_for_struct() {
146136
std::env::set_var("config_foo", "I have been overridden_with_lower_case");
147137

148138
let cfg = Config::builder()
149-
.add_source(File::new("tests/Settings", FileFormat::Jsonc))
139+
.add_source(File::new(&get_config_file_path(""), FileFormat::Jsonc))
150140
.add_source(config::Environment::with_prefix("config").separator("_"))
151141
.build()
152142
.unwrap();
153143

154-
let values: StructSettings = cfg.try_deserialize().unwrap();
155-
assert_eq!(
156-
values.foo,
157-
"I have been overridden_with_lower_case".to_string()
144+
let values: OverrideSettings = cfg.try_deserialize().unwrap();
145+
assert_eq!(values.foo, "I have been overridden_with_lower_case".to_string()
158146
);
159-
assert_ne!(values.foo, "I am bar".to_string());
147+
}
148+
149+
#[derive(Debug, Deserialize, PartialEq)]
150+
enum EnumSettings {
151+
Bar(String),
160152
}
161153

162154
#[test]
163155
fn test_override_uppercase_value_for_enums() {
164156
std::env::set_var("APPS_BAR", "I HAVE BEEN OVERRIDDEN_WITH_UPPER_CASE");
165157

166158
let cfg = Config::builder()
167-
.add_source(File::new("tests/Settings-enum-test", FileFormat::Jsonc))
159+
.add_source(File::new(&get_config_file_path(".enum"), FileFormat::Jsonc))
168160
.add_source(config::Environment::with_prefix("APPS").separator("_"))
169161
.build()
170162
.unwrap();
171-
let val: EnumSettings = cfg.try_deserialize().unwrap();
172163

173-
assert_eq!(
174-
val,
175-
EnumSettings::Bar("I HAVE BEEN OVERRIDDEN_WITH_UPPER_CASE".to_string())
164+
let param = cfg.try_deserialize::<EnumSettings>();
165+
assert!(param.is_err());
166+
assert_data_eq!(
167+
param.unwrap_err().to_string(),
168+
str!["enum EnumSettings does not have variant constructor bar"]
176169
);
177170
}
178171

@@ -181,15 +174,15 @@ fn test_override_lowercase_value_for_enums() {
181174
std::env::set_var("test_bar", "I have been overridden_with_lower_case");
182175

183176
let cfg = Config::builder()
184-
.add_source(File::new("tests/Settings-enum-test", FileFormat::Jsonc))
177+
.add_source(File::new(&get_config_file_path(".enum"), FileFormat::Jsonc))
185178
.add_source(config::Environment::with_prefix("test").separator("_"))
186179
.build()
187180
.unwrap();
188181

189-
let param: EnumSettings = cfg.try_deserialize().unwrap();
190-
191-
assert_eq!(
192-
param,
193-
EnumSettings::Bar("I have been overridden_with_lower_case".to_string())
182+
let param = cfg.try_deserialize::<EnumSettings>();
183+
assert!(param.is_err());
184+
assert_data_eq!(
185+
param.unwrap_err().to_string(),
186+
str!["enum EnumSettings does not have variant constructor bar"]
194187
);
195188
}

tests/testsuite/main.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ pub mod file;
1111
pub mod file_ini;
1212
pub mod file_json;
1313
pub mod file_json5;
14+
pub mod file_jsonc;
1415
pub mod file_ron;
1516
pub mod file_toml;
1617
pub mod file_yaml;

0 commit comments

Comments
 (0)